1 / 37

Java Programming Control Structures Part 2

Java Programming Control Structures Part 2. Phil Tayco San Jose City College Slide version 1.1 February 19, 2019. Code Structures. There are patterns of programming structures in all languages, including Java We’ve discussed 2 types to this point

nquinn
Télécharger la présentation

Java Programming Control Structures Part 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java ProgrammingControl StructuresPart 2 Phil Tayco San Jose City College Slide version 1.1 February 19, 2019

  2. Code Structures There are patterns of programming structures in all languages, including Java We’ve discussed 2 types to this point Sequence: Statement followed by statement and so on Selection: 1 of multiple sequences of code executed based on a logical expression (if…else) The next fundamental structure is “Repetition” Similar to selection, we have a sequence of code that is executed based on a logical expression Key difference is that sequence of code can repeat when the logical expression is re-evaluated We’ll look at this new structure through a somewhat practical example

  3. An Interesting Example Write a program using that calculates the compounded interest of an investment from 3 pieces of information from the user: An initial dollar investment such as 10000.00 An annual interest rate such as 4.5% A number of years to complete such as 5 Calculate and show the total of the investment after the number of years completes based on the annual interest rate Each year, the interest is applied on the latest amount of the investment: After year 1, interest at 4.5% of $10,000 = $450 After year 2, interest at 4.5% of $10,450 = $470.25 After year 3, interest at 4.5% of $10,925.25 = $491.64 Etc. up to after year 5

  4. Program Design Programming problems are often stated in these types of requirements You cannot expect from the sponsor of your program to ask for it in specific programming terms We have to translate the requirements into a design solution to code Often, beginning programmers look at exercises like this and ask how to start Let’s break down the requirements into things we need to design the solution

  5. Program Design A good place to start is to identify variables that may be needed in the program First guideline to remember is that just because we identify a potential variable, doesn’t mean we are locked into using them From the problem statement, there are a few identifiers that stand out: Initial investment Annual interest rate Years to watch investment Final total

  6. Program Design For each potential variable, you want to identify the data type This is sometimes not as trivial as it seems and there are questions to consider: Investment, years and total are numbers, but are they integers or doubles? Interest rate looks like a double, but at what level of precision? Are there any ranges to these numbers? Do these variables have initial values at the start of the program? (Initial being before the user provides the numbers) Based on what we initially know, we can at least declare these variables to start and it is good practice to do so at the beginning of the program

  7. Variable Declarations public static void main(String[] args) { // Variable declarations double investment; double rate; int years; double total; We have at least decided what the variable data types will be Next, we can conceptually decide what ranges and levels of precisions to use Remember that these variables represent storage of values, not presentation Sometimes it is good to document these in the code using comments

  8. Variable Declarations /* investment is expected to be a number greater than or equal to 0.0 rate is expected to be entered by the user as a percentage and stored as its decimal value (user enters 4.5% and rate stores 0.045) years is expected to be an integer greater than or equal to 1 total’s initial value is the investment entered by the user */ Capturing these helps identify how input is expected to be gathered from the user, any checks we may want to do on that data and how they will be stored

  9. Program Design With the initial variable declarations started (remember, there could be more), we can go with designing the rest of the program The requirements in this case can be followed to determine the high level steps of designing a solution: Declare variables Get data from the user Calculate the total Display the result

  10. Program Design This high level of design is a great place to start You can determine the lower level details from each major step in this outline Some major steps don’t have much more detail to complete while others may have more – those can be further broken down in a similar manner This approach is known as “top-level design” and is a good way to break down any design into appropriate details The idea is to identify all the major steps and follow it with detailing each one You may find during the detailing that other major steps are needed, removed or redefined This shows programming is a process and not a final state

  11. User Input In major step 2, we need to get user input, so we’ll need the Scanner The input variable can be declared in the same section as the others – why is this considered to be good practice? When getting the input, we can do simple prompts and data gathering System.out.println("Enter initial investment:"); investment = input.nextDouble(); System.out.println("Enter annual interest rate:"); rate = input.nextDouble(); System.out.println("Enter number of years:"); years = input.nextInt(); total = investment;

  12. Calculating Total Now the fun begins – how to calculate the total The algorithm is basically with each year, calculate the amount earned from the current total investment and interest rate and add the result to the investment Designing this solution for code helps to understand how the repetition structures work (also known as “loops”) The first example of a loop is the “while” loop while (relational expression) { << sequence of code >> } << code after loop >>

  13. Calculating Total This looks a lot like an if…else statement and the pattern is the same The (relational expression) must result in a Boolean value If the value is true, the sequence of code in the loop block is executed When the block of code is complete, control goes back to the relational expression The relational expression is then re-evaluated – if it the result is true, the code sequence in the loop block is executed again The cycle continues until the evaluation of the relational expression results in a value of false When (if) that occurs, control goes to the code after the loop and the while loop is complete

  14. Calculating Total This structure requires developing a thinking process similar to the while loop methodology In English, the while loop is similar to thinking that “as long as xyz is true, repeat steps abc” The challenge is identifying what xyz is and what abc steps to do Loops are designed to execute a certain number of ways, which means they eventually stop xyz is often a relational expression, comparing the value of a variable to another value Part of the key to identifying the relational expression is to look at it from how we want the loop to behave

  15. Calculating Total while (<< 1 to years >>) { << sequence of code >> } While the << 1 to years >> is not a true relational expression, it represents the range of how many repetitions we want to perform The challenge now is defining the expression A true expression will require a relational operator against 2 values years represents the upper limit of the range and the loop is to repeat “as long as” the expression is true

  16. Calculating Total while (1 <= years) { << sequence of code >> } This doesn’t work because “years” is really a fixed value and “1” is not “1” really needs to be represented in another variable that changes as the loop continues This is often referred to as a “loop control variable” which is declared and initialized before the loop

  17. Calculating Total int counter = 1; while (counter <= years) { << sequence of code >> } “counter” could be added to the variable declaration at the beginning or here, just before the loop – what are pros and cons to this? Now we’ve designed how the loop is controlled, next we want to define the sequence of code that will need to be repeated In this case, we are repeatedly recalculating the total based on the current total and annual interest rate

  18. Calculating Total int counter = 1; while (counter <= years) { total = total + (total * rate); } Remember first that total initially equals the value of investment (total * rate) is first calculated – the parentheses in the overall formula follows mathematical rules of precedence The result of that is added to the current value of total The result of the addition becomes the new current value of total There’s an important problem with this code…

  19. Calculating Total int counter = 1; while (counter <= years) { total = total + (total * rate); } Notice that counter starts with an initial value of 1 and is used to control the loop Assuming years is a value greater than or equal to 1, counter <= years at the first evaluation is going to be true The loop body does the calculation but notice that nothing is done to the counter variable As a result, when counter <= years is re-evaluated, it will be true again This will repeat forever and is known as an “infinite loop” error To fix this, loops usually have some change applied to the loop control variable – here, we want to update counter

  20. Calculating Total int counter = 1; while (counter <= years) { total = total + (total * rate); counter = counter + 1; } Adding 1 to counter is simulating doing the calculation for each year The loop starts when we exceed the number in years – at that point, the total should be properly calculated “Updating the loop control variable” in a loop is important to avoid infinite loops There’s a problem with the calculation in this loop

  21. Calculating Total int counter = 1; rate = rate / 100; while (counter <= years) { total = total + (total * rate); counter = counter + 1; } The rate entered is assumed to be in a percentage 4.5 and must first be converted Notice “rate / 100” is not an integer division, do you see why? These are subtle logic errors that are not captured when you compile the program and are harder to spot – welcome to debugging!

  22. Shortcuts int counter = 1; rate = rate / 100; while (counter <= years) { total = total + (total * rate); counter = counter + 1; } You can probably guess that “counter = counter + 1” is a common operation, especially with loops This can simplified for code writing using the “post increment” operator

  23. Shortcuts int counter = 1; rate = rate / 100; while (counter <= years) { total = total + (total * rate); counter++; } Technically, this means to first evaluate the expression before “++” and then add 1 to it after In this case, the expression before it is simply “counter” so nothing really happens except adding 1 to it You could also use pre-increment as “++counter;” and the effect would be the same Pre-increment means add 1 first and then evaluate the expression

  24. Shortcuts int counter = 1; rate = rate / 100; while (counter <= years) { total = total + (total * rate); counter++; } This operation is also common where we want to perform an arithmetic calculation on the current value of a variable and then assign the result to that same variable In this pattern of code, we can use a “compound operator” to simplify the code

  25. Shortcuts int counter = 1; rate = rate / 100; while (counter <= years) { total += (total * rate); counter++; } “+=“ means first perform (total * rate) and add the result to the current value of total and reassign it back All arithmetic operators can be compounded (“-=“, “*=“, “/=“ and “%=“) It effectively simplifies formulas where you see a pattern of “x = x (op) y” to “x (op)= y” Do you see another place in this code to apply a compound operator?

  26. Shortcuts int counter = 1; rate /= 100; while (counter <= years) { total += (total * rate); counter++; } We have one last major step to perform – displaying the result This can easily be handled with a println, but now we have some presentation ideas to consider

  27. Displaying Total System.out.println(total); This will at least show the total and is a good way to develop your code We can test the logic of the code at this point when we run it using various values (what are some good test values to use?) Once we’re satisfied here, we can improve the program by now focusing on the presentation of total This approach is useful because we first focus on the logical behavior and calculations When we follow it with focusing on presentation, we don’t have to think about the logic anymore

  28. Displaying Total System.out.println(“The total is “ + total); This is a simple way to add some text to presenting total Since total is a double data type, the full precision of the number is shown For displaying dollar amounts though, there is a lot of extra information We can refine it by using the “printf” function This is similar to a println with the addition of some elements in the text to allow us to format the text

  29. Displaying Total System.out.printf(“The total is %f“, total); The “%f” in the String is a “format specifier” It’s a code that acts as a placeholder for replacing it with a value provided after the String The values to go into the String are specified after and outside the String with multiple values separated by commas The indicator in the printf String for a specifier is “%” followed by characters to identify the type of data to replace it Different format specifiers are used for specific data types: %f for doubles %d for integers %s for Strings

  30. Displaying Total System.out.printf(“The initial investment is %f and the total is %f“, investment, total); The first “%f” is replaced by the value in investment and the second is replaced by total The order of the values after the String must match the format specifiers in it – if there is a mismatch in numbers, an error will occur The data types must also match, if not, an error will occur as well (this is a common error) The format specifier is the only text that is replaced – surrounding text is displayed literally doubles can be further refined by using “.n” as in “%.2f” to show how many decimal places to present

  31. Displaying Total System.out.printf(“The initial investment is $%.2f and the total is $%.2f“, investment, total); The format specifiers here show only 2 places after the decimal for a double The “$” before the specifier is part of the String for presentation purposes and is not part of the actual format specifier The entire “%.2f” is replaced with the corresponding variable value Any number of format specifiers can be used as long as you have the appropriate number of values appear after the String

  32. Displaying Total System.out.printf(“Over %d years at %.2f%% and an in initial investment is $%.2f, the total is $%.2f“, years, rate, investment, total); The format specifiers are color coded to show the variables with their matching codes Notice %d lines with years, which is an integer Notice there is a “%%” after the specifier for rate – this is not a specifier in itself, but rather a way to literally print the “%” character in a printf Finally, notice that when the String is displayed, the end of the program stops immediately after the String With println, the String is printed followed by going to the next line – not so here with printf We can add special characters to code such actions in the display

  33. Displaying Total System.out.printf(“Over %d years at %.2f%% and an in initial investment is $%.2f, the total is $%.2f\n“, years, rate, investment, total); The “\n” is a character sequence that specifies how to display special characters like new lines and tabs Like the “%” in a format specifier, the special character sequence starts with a “\” The character after is the code for the print to interpret “\n” is used for new lines “\t” for tabs Any number of special character sequences can be used in a String and are each interpreted literally in them println and printf can both use these sequences

  34. Summary Designing a solution from a given set of requirements can be challenging to know how to start The top-down approach provides a systematic way to work through the design process that will involve any number of iterations Three types of fundamental programming structures are sequence, selection, and repetition The while loop is the first example of repetition in Java – we will discuss this more in the next module String presentation offers many ways to show data in code through the use of printf

  35. Programming Exercise 3 Write a basic account management program that interacts with the user as follows Display a menu with 4 options 1) Deposit money 2) Withdraw money 3) Show current balance 4) Project investment 5) Exit Enter option: The user enters an option number from 1-5 Based on the user option selected, a follow up action occurs as described on the next page – when that action is done, the program goes back to the main menu for another user action If option 5 is selected, the program ends

  36. Programming Exercise 3 If option 1 is selected, the program asks “How much to deposit” – the user enters an amount and that amount is added to the current balance If option 2 is selected, the program asks “How much to withdraw” – the user enters an amount and that amount is subtracted from the current balance If option 3 is selected, the program shows the current balance to the user (in proper display format) If option 4 is selected, the program asks the user for the same information in this slide presentation for the compound interest example and calculates the projected final total

  37. Programming Exercise 3 When the program starts, the beginning account balance is $100.00 Do not worry about the user enter incorrect amounts or wrong menu options at this time (you can put controls in if you like for practice) Option 4 in this exercise is a typical programming activity taking existing code (such as what is found in this presentation) and using it in your own program Be careful when copying/pasting this code into your program paying attention to indentation and variable declaration locations During demo, we will review the structure of your code so make sure all indentation, variable naming, and structure is clean

More Related