Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 Loops, Printf Statements, Nested Control Statements and GUI Input & Output Section 1 - While Loops Section 2 - Printf Statements Section 3 -

Similar presentations


Presentation on theme: "Chapter 5 Loops, Printf Statements, Nested Control Statements and GUI Input & Output Section 1 - While Loops Section 2 - Printf Statements Section 3 -"— Presentation transcript:

1

2 Chapter 5 Loops, Printf Statements, Nested Control Statements and GUI Input & Output Section 1 - While Loops Section 2 - Printf Statements Section 3 - For Loops Section 4 - Floating Point Precision & Loop Errors Section 5 - Other Math Class Methods Section 6 - GUI Input & Output Dialog Boxes and Parsing Strings to int and double Go

3 Chapter 5 Section 1 While Loops 2

4 5.1 What are Control Statements? We call …. if statements if-else statements extended if statements while loops and for loops control statements because they control the order of execution in a Java program. 3

5 5.1 General Form of a while loop The while loop executes statements inside its body repeatedly for as long as its boolean condition remains true. Every time the statements inside a while loop run, we say one iteration, one pass, or one repetition has occurred. while (condition) No semicolon goes here! { statement; } No curly braces required for just one line of code in the loop. 4

6 5.1 A while loop Stops with a False Condition When the boolean condition of a while loop becomes false, the while loop will stop. There should be some code in the loop to make it stop, otherwise you will have an infinite loop (never-ending loop). while (condition) No semicolon goes here! { statement; } No code is executed if the boolean condition is initially false. The loop is skipped! 5

7 5.1 A Count Up while Loop Example A count-up while loop can be written to sum the integers from 1 to 3: int sum = 0; int cntr = 1; while (cntr <= 3) { sum += cntr; cntr++; } System.out.println(sum); Notice that here cntr, the loop control variable, is initialized to 1 before the loop and then it is incremented by 1 each time the body of the loop is executed. When cntr becomes 4, then the while loop condition will evaluate to false and the loop will immediately end. Since the loop control variable cntr increases by 1 every time the body of the loop executes, we call it a count-up loop. 6

8 5.1 Tracing a Count Up while Loop It is important to be able to trace the order of execution of a while loop to be able to fully understand how it works: int sum = 0; 1 int cntr = 1; 2 while (cntr <= 3) 3 6 9 12 { sum += cntr; 4 7 10 cntr++; 5 8 11 } System.out.println(sum); 13 Note: you are not required to used cntr in the mathematics or work of the loop as in the line sum += cntr; We just happen to be using it here as an easy way to help sum the numbers from 1 to 3. 7 The blue numbers indicate the order the lines of code are executed in.

9 5.1 Skeleton of a Count Up while Loop If you initially think about the problem of summing the numbers from 1 to 100, you should conclude that a loop is needed that will run 100 times. So the place to start is just to think about the basic parts of the loop that you need. Don’t worry about the mathematics or the work to be done inside the loop. Pull the necessary components together that will give you a loop that will run 100 times. Here is where you should start: int cntr = 1; while (cntr <= 100) { cntr++; } declare and initialize the loop control variable design a loop condition that will make the loop run the correct number of times increment the loop control variable at the bottom of the loop so the loop will eventually stop. 8

10 5.1 Adding other Lines to a while Loop Next, declare and initialize any additional variables needed for the mathematics that will make the loop calculate the correct value. These should be added before the loop! Then, add the appropriate lines of code inside the loop to make the calculation. int sum = 0; int cntr = 1; while (cntr <= 100) { sum += cntr; cntr++; } System.out.println(“The sum is: ” + sum); declare and initialize other variables add the lines of code to the loop necessary to make the calculation. 9 The value 5050 is printed.

11 5.1 Varying while Loops Conditions What if the boolean expression of the original code was changed from: cntr <= 100 to cntr < 100 int sum = 0, cntr = 1; while(cntr < 100) { sum += cntr; cntr++; } Then the loop runs only 99 times instead of 100 and the value stored in sum is 4950 instead of 5050. 10

12 5.1 Count-Controlled while Loops The variable cntr is the counter variable or loop control variable (lcv) and is declared and initialized before the while loop. This while loop repeats 100 times, because when the loop is encountered the value of cntr is 1 and it is incremented by 1 every time the body of the loop runs. The loop will run the final time when cntr is 100 and then when it becomes 101 inside the loop, then the loop condition evaluates to false and the body of the loop won’t execute anymore. Consider the following code that sums the integers from 1 to 100: int sum = 0; int cntr = 1; while(cntr <= 100) { sum += cntr; cntr++; } The sum is calculated as the number 5050. In a count-controlled loop, the loop control variable is incremented by one each time the loop runs.

13 5.1 Summing from 51 to 100 If we wish to sum the numbers from 51 to 100, then we only need to make a slight variation in our code by changing the value that we initialize cntr to … 51. int sum = 0; int cntr = 51; while (cntr <= 100) { sum += cntr; cntr++; } System.out.println(“The sum is: ” + sum); 12

14 5.1 Summing from 51 to 150 If we wish to sum the numbers from 51 to 150 instead of 100, then we also need to change the upper limit value of the loop. int sum = 0; int cntr = 51; while (cntr <= 150) { sum += cntr; cntr++; } System.out.println(“The sum is: ” + sum); 13

15 5.1 Count Down while Loops Countdown Loop code: int sum = 0; int cntr = 100; while(cntr >= 1) { sum += cntr; cntr--; } Note the main line of code in the loop is the same. Only the loop header and the initialization value of the lcv have been changed and the use of the decrement operator instead of the increment operator. Compare the two codes to see the differences. The following code uses a variation of the previous code to sum the integers from 100 down to 1. We call this a count down loop: Original code: int sum = 0; int cntr = 1; while(cntr <= 100) { sum += cntr; cntr++; } 14

16 5.1 Reverse Summing with a Count Down Loop Here is a while loop that REVERSE sums the numbers from 51 to 100 by adding them like this 100 + 99 +.... + 52 + 51. sum = 0; cntr = 100; while(cntr >= 51) { sum += cntr; cntr--; } System.out.println("The Reverse sum of 100 to 51 is: " + sum); 15

17 5.1 A Count-Down that Decrements by 5 You can make a loop control variable decrease in value as well as increase. It can decrease by 1 or by any other value you indicate. Here number is the loop control variable. int number = 25; while (number >= 10) { System.out.print("The square root of " + number); System.out.println(” is " + Math.sqrt(number)); number -= 5; } Output in console window: The square root of 25 is 5.0 The square root of 20 is 4.47213595499958 The square root of 15 is 3.872983346207417 The square root of 10 is 3.1622776601683795 16

18 5.1 A Count-Down While Loop Variation What if the boolean expression was changed from: number >= 10 to number > 10 int number = 25; while (number > 10) { System.out.print("The square root of " + number); System.out.println(” is " + Math.sqrt(number)); number -= 5; } The loop runs one less times and the Output is: The square root of 25 is 5.0 The square root of 20 is 4.47213595499958 The square root of 15 is 3.872983346207417 17

19 5.1 Task-Controlled While Loops A loop can execute until some task is accomplished. This code seeks to find the value of number once sum is greater than 1,000,000. int sum = 0; int number = 0; while ( sum <= 1000000) { number++; sum += number; } System.out.print(“The first value of number for which”); System.out.println(“ sum is over 1,000,000 is: " + number); In this example, the loop control variable is sum but it is not incremented by one or any other constant value each time the loop runs. 18

20 5.1 Interesting While Loop Example Code Example: Generate a random integer between -5 and 5 inclusive and store it in x. If x is positive find the square root of all values between 1 and x and print them out, otherwise do nothing. int x = (int) (Math.random() * 11 ) - 5; while (x > 0) { double root = Math.sqrt(x); System.out.println(“The square root of x is ” + root); x--; } Notice that if the value stored in x is between -5 and 0 inclusive, the loop will NOT run at all. Also notice that when x is positive, the loop will run and then x will be decremented by 1 and eventually x will become 0 and when it does then 0 > 0 evaluates to false and the loop stops. 19

21 5.1 User-Controlled While Loop Example The following code sums all the integers between two integers (inclusive) entered from the keyboard: Scanner reader = new Scanner (System.in); System.out.print(“Enter a starting value: ”); int startingValue = reader.nextInt(); System.out.print(“Enter an ending value greater than starting value: ”); int endingValue = reader.nextInt(); int sum = 0; int cntr = startingValue; while (cntr <= endingValue) { sum += cntr ; cntr++; } System.out.println(sum); 20

22 5.1 Generate 10 Random Integers The following code prints 10 random integers in the range of 25 to 75 inclusive: int cntr = 1; while (cntr <= 10) { int x = (int) (Math.random() * 51) + 25; System.out.println("The random integer is " + x); cntr++; } Note: here we want to print each random integer, so our System.out.println statement is inside the loop. 21

23 5.1 Entering Values from the Keyboard in a Loop The following loop runs 5 times and asks the user to enter a vocab word each time the loop runs. The vocab word is then printed out. int cntr = 1; while (cntr <= 5) { System.out.print("Enter a vocab word and press return: "); String word = reader.nextLine(); System.out.println(); System.out.println(”The vocab word is: " + word); System.out.println(); cntr++; } 22

24 5.1 Branching Statements Inside While Loops Branching statements may be nested or placed inside loops. Almost every programming problem can be solved with the combination of loops and branching statements. The following code prints whether each integer between 1 and 10 is even or odd. int cntr = 1; while (cntr <= 10) { if (cntr % 2 == 0) System.out.println(cntr + “ is even”); else System.out.println(cntr + “ is odd”); cntr++; } 23

25 5.1 Branching Statements Inside Loops Notice that we could also use … int cntr = 1; while (cntr <= 10) { if (cntr % 2 == 0) System.out.println(cntr + “ is even”); else if (cntr % 2 == 1) System.out.println(cntr + “ is odd”); cntr++; } 24

26 5.1 Branching Statements Inside Loops Again, many programming problems are solved with the combination of loops and branching statements. You will solve a lot of problems with loops and branching statements in the programs that you will write in this chapter. 25

27 5.1 A While Loop May Never Run // Why does the following loop never run? int a = 100; int b = 50; while (a < b) { System.out.println("This will print if the loop runs!"); a += b; } System.out.println("The value of a is: " + a); System.out.println("The value of b is: " + b); System.out.println("The loop never runs!!! "); 26

28 5.1 While Loops That Never Ends … Infinite Loops A while loop that never ends is called an infinite loop. Here is an example of a loop that starts but never ends. Can you tell why? int a = 0; int b = 101; while (a != b) { a += 2; } System.out.println(“The value of a is ” + a); 27

29 5.1 While Loops That Never Ends … Infinite Loops A while loop that never ends is called an infinite loop. Here is an example of a loop that starts but never ends. Can you tell why? int a = 0; int b = 101; while (a != b) // use of != causes the infinite loop { a += 2; } System.out.println(“The value of a is ” + a); Changing != to <= causes the loop to run Changing != to >= causes the loop to be skipped 28

30 5.1 Order & Structure of a While Loop 1)Initialize the loop control variable and other variables. 2)Test the loop control variable in the condition to try to enter the while loop. 3)If successful entry, execute the body of the loop and then perform calculations and change the lcv or other variables. 4)When the condition becomes false, the loop stops without executing the body. initialize loop control variable // initialize while (condition) // test the loop control variable in the condition {// execute the body of loop perform calculations and change the lcv or other variables involved in the condition } 29

31 5.1 Using a while (true) loop with Break Since true is a valid boolean value, a while(true) loop can be used. A while (true) loop continues to run until some condition makes it stop. This can be done by embedding a break statement inside an if statement inside the loop, so that when the if condition becomes true, the break statement will be executed and the loop will immediately stop. while (true) { System.out.print(“Enter a number or -1 to quit: ”); int x = reader.nextInt(); if (x == -1) break; …. // lines of code that use x if it is not -1 } -1 is called the sentinel because it makes the loop stop 30

32 5.1 A while (true) loop Example Here is a while-true loop example that … while(true) { System.out.print("Enter the person's age or -1 to quit: "); age = reader.nextInt(); if (age == -1) break; reader.nextLine(); // consume the new line character System.out.print("Enter the person's name: "); name = reader.nextLine(); if(age 120) System.out.println("There is NO WAY you are alive " + name); else { System.out.println("The name of the person is: " + name); System.out.println("The age of the person is: " + age); } } // end of while(true) loop 31

33 5.1 Flow Chart for The while Statement 32 boolean condition Statements true false Statements after loop Notice the return arrow after the last statement in the loop. It makes contact above the condition diamond. All the statements inside the loop go here.

34 Chapter 5 Section 2 Formatting Console Output with printf statements 33

35 5.2 Introduction to printf statements print and println statements don’t allow us to easily format output to the screen or a file in an organized manner. However, a printf statement does. Just like the ln in println is an abbreviation for line. The f in printf is an abbreviation for format. Many times when we use loops to output a lot of data to the screen, we want it to be more readable. We can use printf statements to make output more readable by placing data in columns. printf statements allow us to left justify output or right justify output. You can use both in the same statement to do things like start printing at the left margin but align other output in columns. This makes the output more readable to the user of a program. Freezing = 3 2 Boiling = 2 1 2 Fiery = 5 1 3 4 Nice = 8 7 Super Hot = 6 9 2 4 1 The words are left justified. The integers are right justified. 34

36 5.2 The Form of a printf Statement A printf statement always has the following form: System.out.printf ("format string", dataValue1, dataValue2,....); Notice the format string and all data values are separated by commas NOT + signs. The format string is inside double quotes and there must be a format specifier in it for each data value listed in the remainder of the statement. You can have any number of data values, but you must have one format specifier for every data value. The data values are NOT within double quotes unless they are String values. Format specifiers always begin with the % symbol. 35

37 5.2 printf Statement Examples Here are three examples of printf statements. int fahrenheit = 212; double percentage = 97.524791; String phrase = “Java is Cool!”; System.out.printf ("%7d”, fahrenheit); System.out.printf ("%10.4f”, percentage ); System.out.printf ("%20s”, phrase); We will explain what is in the parentheses of each printf statement above shortly. 36

38 5.2 The printf Format Specifiers There are three primary format specifiers that we will use: the letter d for decimal (base-10) int values as in %7d the letter f for decimal floating point values as in %10.4f the letter s for string values as in %20s %n is a format specifier that tells Java to display a new-line character, but you can also use the escape sequence \n in its place. When Java sees %n, it knows not to apply it to any data value after the format string. If a dash - follows the % symbol of a format specifier, then the data value will be left justified. If there is no dash then the data value is automatically right justified. The - is called a format flag. You’ll see examples coming up. 37 decimal doesn’t indicate decimal point

39 5.2 The Format Specifier for int printf statements can right justify integer output. Consider this code: int fahrenheit = 212; System.out.printf("%7d”, fahrenheit); Once java sees the format specifier %7d then it retrieves the int data value stored in the variable fahrenheit (212) after the comma. Java figures out that it needs 3 spaces to print 212 and then it calculates that it needs 7-3 spaces or 4 spaces before 212 since it is right justifying the output. So it skips 4 spaces from the left and then begins printing 212. It prints 212 in the 5th, 6th, and 7th spaces of the field width of 7 spaces. If we use an underscore character ‘_’ to represent a blank space, then the output would look like this: _ _ _ _ 212 The printf statement right justifies the value stored in the variable fahrenheit in a field width of 7 spaces. 38

40 5.2 The Format Specifier for int We can also add other string information inside the quotation marks of the format string that we also want printed out prior to 212: int fahrenheit = 212; System.out.printf(“Temperature = %7d”, fahrenheit); Java will first print Temperature = at the first of a line of output and then when it sees the format specifier %7d it retrieves the int data value stored in the variable fahrenheit (212). Again, Java figures out that it needs 3 spaces to print 212 and then skips 4 spaces from the left of the last thing printed and then begins printing 212. The output would look like the following with underscores again representing blank spaces: Temperature = _ _ _ _ 212 39

41 5.2 The Format Specifier for int We can also add other string information inside the format string that we want printed out after 212: int fahrenheit = 212; System.out.printf(“Temperature = %7d Fahrenheit”, fahrenheit); Java will first print Temperature = and then when it sees the format specifier %7d then it retrieves the int data value stored in the variable fahrenheit (212) and prints it right justified in the field width of 7. It then prints the word Fahrenheit after 212. The output would look like the following: Temperature = _ _ _ _ 212 Fahrenheit Make sure you realize that the %7d applies to fahrenheit the variable NOT Fahrenheit the word. 40

42 5.2 The Format Specifier for int You might be wondering … “Why would we want to use %7d?” The reason is a program may need to output temperature values of different sizes with all of the ones digits lined up, all of the tens digits lined up, all of the hundreds digits lined up, etc. In other words, we would want output to look like this with the numbers right justified: Temperature = _ _ _ _ _ 3 2 Fahrenheit Temperature = _ _ _ _ 2 1 2 Fahrenheit Temperature = _ _ _ 5 1 3 4 Fahrenheit Temperature = _ _ _ _ _ 8 7 Fahrenheit Temperature = _ _ 6 9 2 4 1 Fahrenheit 41

43 5.2 The Format Specifier for int You may be wondering what would Java do if the temperature was over 9,999,999, then Java would have to take an extra space to print all of the digits of the temperature (because it won’t chop the number off) and then the formatting would be off on that one line as seen below. Temperature = _ _ _ _ _ 3 2 Fahrenheit Temperature = _ _ _ _ 2 1 2 Fahrenheit Temperature = _ _ _ 5 1 3 4 Fahrenheit Temperature = _ _ _ _ _ 8 7 Fahrenheit Temperature = 3 7 5 6 9 2 4 1 Fahrenheit So it is important to choose a field width that is larger than the biggest number you expect to have in output. 42

44 5.2 Right Justified Output for int Here are random integers between 1 and 2000 that are right justified using a prinf statement with a field width of 4. Notice the ones digits, tens digits, hundreds digits, and thousands digits are lined up. 1102 295 1493 536 3 424 47 1983 1995 740 43

45 5.2 Left Justification for int You can use a printf statement to left justify output also. Consider the code: int fahrenheit = 212; System.out.printf ( "%-7d”, fahrenheit ); Once java sees the format specifier %-7d then it retrieves the data value stored in the variable fahrenheit (212). Java figures out that it needs 3 spaces to print 212 and then begins printing 212 at the left margin. It then advances 4 spaces to get ready to print the next thing. It prints 212 in the 1st, 2nd, and 3rd spaces of the field of 7 spaces. The output would look like the following: 2 1 2 _ _ _ _ The printf statement uses the - format flag to left justify the value stored in the variable fahrenheit in a field width of 7 spaces. 44

46 5.2 The Format Specifier for double printf statements can be set to round what is printed out. They don’t actually round what is in the variable, but they round what is seen on the screen. In this example, we will print right justified a floating point value in a field width of 10 with a precision of 4. double percentage = 99.3456789; System.out.printf (“ %10.4f ”, percentage ); Once java sees the format specifier %10.4f then it retrieves the data value stored in the variable percentage (99.3456789). Java figures out that it needs 4 spaces to print the part of the number to the right of the decimal point. It uses the number in the 5th decimal place (7) to round the number to.3457. It then uses the remaining spaces: 10 - 4 = 6 to print the decimal point and the part of the number to the left of the decimal point. Note how the number is rounded when it is printed. The output would look like the following: _ _ _ 9 9. 3 4 5 7 45

47 5.2 Left Justification for double We can use a printf statement to round but use left justification instead. In this example, we will print left justified a floating point value in a field width of 10 with a precision of 4. double percentage = 99.3456789; System.out.printf (“ %-10.4f ”, percentage ); Note how the number is rounded and left justified when it is printed. Any other output will start after the 3 blank spaces. The output would look like the following: 9 9. 3 4 5 7 _ _ _ 46

48 5.2 The Format Specifier for String printf statements can be used to display string information left or right justified. In this example, we will print right justified a string value in a field width of 20. String phrase = “Java is Cool!”; System.out.printf (“ %20s ”, phrase); Once java sees the format specifier %20s then it retrieves the data value stored in the variable phrase (“Java is Cool!”). Java figures out that it needs 13 spaces to print phrase, including any spaces between the words. It uses the remaining spaces: 20 - 13 = 7 to print 7 spaces before phrase. The output would look like the following: _ _ _ _ _ _ _ J a v a _ i s _ C o o l ! 47

49 5.2 Left Justification for Strings In this example, we will print left justified a string value in a field width of 20. String phrase = “Java is Cool!”; System.out.printf (“ %-20s ”, phrase); Once java sees the format specifier %-20s then it retrieves the data value stored in the variable phrase(“Java is Cool!”). Java figures out that it needs 13 spaces to print phrase. It uses the remaining spaces: 20 - 13 = 7 to print 7 spaces after phrase. Any other output has to begin after those 7 spaces. The output would look like the following: J a v a _ i s _ C o o l ! _ _ _ _ _ _ _ 48

50 5.2 The New Line Format Specifier None of the previous examples start a new line after printing the data values. To start a new line after printing the data value, the new line format specifier %n is added in the format string. All of the lines below will print the data values and start a new line. System.out.printf(“%7d%n”, fahrenheit); System.out.printf(“%-7d%n”, fahrenheit); System.out.printf(“%10.4f%n”, percentage ); System.out.printf(“%-10.4f%n”, percentage ); System.out.printf(“%20s%n”, phrase); System.out.printf(“%-20s%n”, phrase); Note: when Java sees the %n format specifier, it doesn’t look for a data value to the right of the comma like it does with other format specifiers. Notice there doesn’t need to be a space between any two format specifiers. If you put one, it will be added to output. 49

51 5.2 The New Line Format Specifier You can choose to use \n in the place of %n. So the code on the previous slide could be changed to: System.out.printf(“%7d\n”, fahrenheit); System.out.printf(“%-7d\n”, fahrenheit); System.out.printf(“%10.4f\n”, percentage ); System.out.printf(“%-10.4f\n”, percentage ); System.out.printf(“%20s\n”, phrase); System.out.printf("%-20s\n”, phrase); 50

52 5.2 Multiple Format Specifiers in One Line All of the previous printf statements have only one data value that is formatted whether a new line is created or not. Numerous format specifiers and data values can be included in one printf statement. All of the format specifiers must appear in the format string between the double quotes. System.out.printf("%7d%10.4f%20s%n”, fahrenheit, percentage, phrase); The output all on one line would look like this: ____212___99.3457_______Java is Cool! Note there are commas to separate each of the variables that represent data values. 51

53 5.2 Multiple Format Specifiers in One Line Sometimes we want to have numerous format specifiers and data values in one printf statement, but we want to also print out additional string information. Here is an example of how you might do that: …. loop that calculates the square and cube of a set of numbers and then uses the following printf statement … (i is the lcv) System.out.printf("The square of %5.1f is %6.1f and the cube is %7.1f%n", i, square, cube); The output for each line of output would look something like this: The square of 1.0 is 1.0 and the cube is 1.0 The square of 2.0 is 4.0 and the cube is 8.0 The square of 3.0 is 9.0 and the cube is 27.0 The square of 4.0 is 16.0 and the cube is 64.0 The square of 5.0 is 25.0 and the cube is 125.0 52

54 5.2 Multiple Format Specifiers in One Line When printf statements get too long, you can break them up into separate printf statements. Compare these two different ways of printing the exact same thing: System.out.printf("The square of %5.1f is %6.1f and the cube is %7.1f%n", i, square, cube); and System.out.printf(“The square of %5.1f is %6.1f”, i, square); System.out.printf(“ and the cube is %7.1f%n", cube); both produce … The square of 1.0 is 1.0 and the cube is 1.0 The square of 2.0 is 4.0 and the cube is 8.0 The square of 3.0 is 9.0 and the cube is 27.0 The square of 4.0 is 16.0 and the cube is 64.0 The square of 5.0 is 25.0 and the cube is 125.0 53

55 5.2 Multiple Format Specifiers in One Line Sometimes we can print the same thing using separate printf statements where we want to left or right justify the string information but we don’t want the info in the format string. Here is the original printf statement: System.out.printf("The square of %5.1f is %6.1f and the cube is %7.1f%n", i, square, cube); Here is one that splits the original into two printf statements that formats the strings using format specifiers, but it left justifies both “The square of” and “and the cube is” treating them as data values. System.out.printf(“%-14s%5.1f is %6.1f”, “The square of”, i, square); System.out.printf(“%-15s%7.1f%n”, “and the cube is”, i, cube); 54

56 5.2 The Comma Format Flag for Numbers The comma format flag makes large numbers even more readable. Here is an example: Let’s assume we have calculated the 8th perfect number and we want to print it with commas. We could use the line of code: System.out.printf ("The 8 th Perfect Number is %,30d", num); This gives the output: The 8 th Perfect Number is 2,305,843,008,139,952,128 It is worthwhile to note that d will not only format int values but also long values and this value is in the long range. 55 note the comma

57 Chapter 5 Section 3 For Loops 56

58 5.3 Definition of a For Loop In Java you can execute a segment of code over and over again using a “for” loop. The key difference between a for and a while loop is you can place the declaration and initialization of the lcv (loop control variable), the test condition, and the lcv update statement all in the for loop header. A for loop looks like this: for (declare & initialize lcv; test condition; update lcv) { } No code is executed if the test condition is initially false. Note the curly braces { } that encompass all of the statements inside the for loop body. 57

59 5.3 Skeleton of a for Loop for (int cntr = 1; cntr <= 3; cntr++) { } int cntr = 1; while (cntr <= 3) { cntr++; } Here we compare the skeleton of a for loop with the skeleton of a while loop. Each of these loops is designed to iterate three times. Observe the placement of the lcv (loop control variable) cntr in the two different loops. 58

60 5.3 A Simple for Loop Example int sum = 0; for (int cntr = 1; cntr <= 3; cntr++) { sum += cntr; } System.out.println(sum); int sum = 0; int cntr = 1; while (cntr <= 3) { sum += cntr; cntr++; } System.out.println(sum); Any while loop can be written as a for loop and vice-versa. Here is the code to sum the integers from 1 to 3. Compare it to the while loop version of the code. Again, observe the placement of the lcv (loop control variable) cntr in the two different loops. The next slide will show you the order of execution of the statements in the for loop. 59

61 5.3 The for Loop Order of Execution It is important to be able to trace the order of execution of a for loop. This will help you fully understand what is going on. The order of execution is indicated with the blue numbers. int sum = 0; for (int cntr = 1; cntr <= 3; cntr++) this is the for loop header { sum += cntr; } System.out.println(sum); Note: the loop control variable cntr is updated at the bottom of the loop, after the statements in the body have been executed. 1 2 3 6 9 12 4 7 10 5 8 11 13 Having cntr++ in the for loop header is like having cntr++ here 60

62 5.3 A Second While & For Loop Comparison Compare the parts of the for loop and while loop versions of the code that sums all of the integers from 1 to 100: int sum = 0; for (int cntr = 1; cntr <= 100; cntr++) { sum += cntr; } System.out.println(sum); int sum = 0; int cntr = 1; while (cntr <= 100) { sum += cntr; cntr++; } System.out.println(sum); For loops provide an efficient way to write quickly the skeleton of a loop and help you avoid loop errors. For loops are actually more readable, because you can see on one line if all of the necessary parts are present. 61

63 5.3 Setting Up A Count Up for Loop If you initially think about the problem of summing the numbers from 1 to 100, you should conclude that a loop is needed that will run 100 times. So the place to start is just to think about the basic parts of the loop that you need. Don’t worry about the mathematics or the work to be done. Pull the necessary components together that will give you a loop that will run 100 times. Here is where you should start: for (int cntr = 1; cntr <= 100; cntr++) { } declare and initialize the loop control variable design a loop condition that will make the loop run the correct number of times increment the loop control variable so the lcv will change and the loop will eventually stop. 62

64 5.3 Adding Other Lines to a for Loop Next, declare and initialize any additional variables needed for the mathematics that will make the loop calculate the correct value. These should be added before the loop! Then, add the appropriate lines of code inside the loop to make the calculation. int sum = 0; for (int cntr = 1; cntr <= 100; cntr++) { sum += cntr; } System.out.println(“The sum is: ” + sum); add the lines of code to the loop necessary to make the calculation. 63 declare and initialize other variables The value 5050 is printed.

65 5.3 Summing from 51 to 100 If we wish to sum the numbers from 51 to 100, then we only need to make a slight variation in our code by changing the value that we initialize cntr to … 51. int sum = 0; for (int cntr = 51; cntr <= 100; cntr++) { sum += cntr; } System.out.println(“The sum is: ” + sum); 64

66 5.3 Summing from 51 to 100 If we wish to sum the numbers from 51 to 150 instead of 100, then we also need to change the upper limit value of the loop. int sum = 0; for (int cntr = 51; cntr <= 150; cntr++) { sum += cntr; } System.out.println(“The sum is: ” + sum); 65

67 5.3 Summing Random Integers Write a for loop that will print 100 random integers in the range from 1 to 300 inclusive. The loop should print each random integer as it is generated inside the loop, but print only 5 random integers per line. System.out.println("Here are 100 random ints 5 per line."); for(int cntr = 1; cntr <= 100; cntr++) { int x = (int) (Math.random() * 300) + 1; System.out.printf("%7d", x); if (cntr % 5 == 0) System.out.println(); } 66

68 5.3 Reverse Summing from 100 to 51 If we wish to reverse sum the numbers from 100 down to 51, then we only need to make a slight variations in our code …. int sum = 0; for (int cntr = 100; cntr >= 51; cntr--) { sum += cntr; } System.out.println(“The sum is: ” + sum); 67

69 5.3 A Count-Down for Loop A count-down for loop can be used similar to a while loop: // Display the square roots of 25, 20, 15, and 10 for ( int number = 25; number >= 10; number -= 5) { System.out.println(“The square root of ” + number + “ is ” + Math.sqrt(number)); } Notice as before with a while loop the test condition uses >= instead of instead of < also. 68

70 5.3 Count-Controlled Input with a for Loop This code sums a list of numbers entered from the keyboard. You will find that i is used a lot as a loop control variable. This is by tradition. double number; double sum2 = 0; System.out.print(“How long is the list? ”); int count = reader.nextInt(); for (int i = 1; i <= count; i++) { System.out.print(“Enter a positive number: ”); number = reader.nextDouble(); sum2 += number; } Note: the letter i has long been used as a lcv. This is a tradition that has continued over the years with programmers. 69

71 5.3 String Input in a for Loop Write a for loop that will run 5 times and allow the user to enter a vocabulary word from the keyboard each time the loop runs. The word will be printed after it is received from the keyboard along with how many characters are in the word. String word = “”; // initialized to empty string for (int i = 1; i <= 5; i++) { System.out.print(“Enter a vocab word: ”); word = reader.nextLine(); System.out.print("The number of characters in " + word + " is "); System.out.println( word.length() ); } 70

72 5.3 A for Loop May Never Run Why won’t the for loop seen here run? int b = 50; int a; for(a = 100; a < b; a++) { System.out.println("This will print if the loop runs!"); a += b; } System.out.println("The value of a is: " + a); System.out.println("The value of b is: " + b); System.out.println("The for loop never runs!!! "); 71

73 5.3 For Loops That Never Ends … Infinite Loops A for loop that never ends is also called an infinite loop. Here is an example of a for loop that starts but never ends. Can you tell why? int d = 50; for(int c = 1; c != 300; c += 2) { d += 100; } System.out.println("The value of d is " + d); 72

74 5.3 Nan Stands for Not A Number BY THE WAY … "NaN" stands for "not a number". "Nan" is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Taking the square root of a negative number is also undefined. 73

75 Chapter 5 Section 4 Floating Point Precision Loop Errors

76 5.4 Effects of Floating-Point Precision Normally, we don’t use double variables as loop control variables, we use int variables. However, if you need to for some reason, you need to understand that not all double values can be represented accurately in Java in a program. If we divide 1.0 / 3, we know the answer is a repeating decimal of 0.3 However, this value cannot be accurately represented by the computer. At some point, Java must terminate it. It is being converted to binary so the division can take place and then back to base-10. In running the following code: double num = 1.0 / 3; num will hold the value 0.3333333333333333 See the next slide to see how this could cause a problem. 75

77 5.4 Approximate Floating-Point Precision Numbers that are declared as double have about 18 decimal digits of precision. This is good but is not perfect and can lead to unexpected errors. Here is an example: for (double x = 0.0; x != 1.0; x+= 0.1) { System.out.println(x + " "); } This code goes into an infinite loop because of the use of the line x != 1.0; The line x <= 1.0 should be used. Here is what happens: the base-10 versions of 0.0 and 0.1 are converted to binary and every time 0.1 is added to x, the binary equivalent of 0.1 is added to x. As x grows and it is printed, it is converted back to base 10 where there is a loss of accuracy. So … 76

78 5.4 Approximate Floating-Point Precision … what is printed out is not 0.0, 0.1, 0.2, 0.3, 0.4, etc. but rather 0.0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 1.0999999999999999 … unending output indicating an infinite loop 77

79 5.4 Debugging Errors in Loops If an error is suspected, check these four things: make sure all variables including the loop control variable are initialized correctly before entering the loop that the terminating condition stops the loop when the loop control variable or other test variables have reached the intended limit that the statements in the body of the loop are correct that the update statement is positioned correctly and that it modifies the loop control variable or other test variables so that they eventually pass the limits tested in the terminating condition so the loop will stop 78

80 Chapter 5 Section 5 Other Math Class Methods 79

81 5.5 Other Math Class Methods The Math class has numerous other methods that are static and can be called in the same manner that Math.abs(), Math.pow(), Math.sqrt(), and Math.random() are called by prefixing the method by the name of the class. Here are some other methods we will use: public static double log10 (double a) public static double sin (double a) public static double cos (double a) public static double tan (double a) public static double toRadians (double angleDegrees) 80

82 5.5 The Math Class Log10 Method If you want to find the base 10 logarithm of a number you can use the method Math.log10(). The method signature is as follows: public static double log10 (double a) If the parameter a is equal to 10 n for integer n, then the result is n. Examples:Math.log10 (10) returns 1 Math.log10 (100) returns 2 Math.log10 (1000) returns 3 Math.log10 (10000) returns 4 81

83 5.5 The Math Class Log Method If you want to find the base e logarithm (natural logarithm) of a number you can use the method Math.log(). The Math class has the constant E and it can be used by writing Math.E where E is “the double value that is closer than any other to e, the base of the natural logarithms.” You may know that the constant is a non- terminating decimal like PI that is represented by the number 2.71828182845904523536028747135266249775724709369995... (from WikiPedia) The method signature is as follows: public static double log (double a) Returns the natural logarithm (base e) of a double value. Even though we won’t use it, it is worth knowing that Java has the constant E and the method Math.log(). 82

84 5.5 The Math Class toRadians Method Before some trigonometric calculations, like sine, cosine, and tangent, can be made in Java, angle measures must be converted to radians. This can be done using the toRadians() method. public static double toRadians (double angleDegrees) The API says that this method converts an angle measured in degrees to an approximately equivalent angle measured in radians.Example: double angle = 30.0; double radians = Math.toRadians(angle); 83

85 5.5 The Math Class Sin Method If you want to find the sine of an angle, then you can convert an angle first to radians and then call the sin() method. The method signature is as follows: public static double sin (double a) This method returns the trigonometric sine of an angle, where the parameter a is in radians. Sample code use: double angle = 30.0; double radians = Math.toRadians(angle); double sine = Math.sin(radians); 84

86 5.5 The Math Class Cos Method If you want to find the cosine of an angle, then you can convert an angle first to radians and then call the cos() method. The method signature is as follows: public static double cos (double a) This method returns the trigonometric cosine of an angle, where the parameter a is in radians. Sample code use: double angle = 30.0; double radians = Math.toRadians(angle); double cosine = Math.cos(radians); 85

87 5.5 The Math Class Tan Method If you want to find the tangent of an angle, then you can convert an angle first to radians and then call the tan() method. The method signature is as follows: public static double tan(double a) This method returns the trigonometric tangent of an angle, where the parameter a is in radians. Sample code use: double angle = 30.0; double radians = Math.toRadians(angle); double tangent = Math.tan(radians); 86

88 Chapter 5 Section 6 GUI Input & Output Dialog Boxes 87

89 5.6 The JOptionPane Class The JOptionPane class allows us to use dialog boxes to receive input and to display output. For input, we us … JOptionPane.showInputDialog(); and for output we use … JOptionPane.showMessageDialog(); 88

90 5.6 Receiving Input Using showInputDialog A convenient way to accept input from a user, even in a console program, is to use an input dialog box that prompts the user to enter a value by calling the method showInputDialog of the JOptionPane class: String inputStr = JOptionPane.showInputDialog(null, "Enter the radius", "0"); Notice the method requires 3 parameters. Null is a necessary first parameter if this line does not appear in an applet program. The prompt “Enter the radius” is the second parameter and a default value (here zero) is the third parameter and appears in the text entry field. The user can use the default value or enter something else like 10 and then click OK. 89 Notice there is also a Cancel button.

91 5.6 Canceling an Input Dialog Box When using an input dialog box, a programmer should build in protection in case the user decides not to enter a value and clicks Cancel instead. If the code for an input dialog box is in a method, we can add the following code to terminate the input process and the method: String inputStr = JOptionPane.showInputDialog(null, "Enter the radius", "0"); if (inputStr == null) return; This works because if the user clicks cancel the value null is returned instead of some number in string form. Maybe you remember that when a String variable is declared but not initialized or given a value, it then references the value null. This is why we can use if (inputStr == null) to see if cancel was clicked. 90

92 5.6 Parsing Numeric Input All values from an input dialog box are returned as String values. So if the expected input is a number, you must parse it using either … Integer.parseInt() or Double.parseDouble() These methods convert the input String value to an int or double number so the input can be processed as a number. parseInt() and parseDouble() are static methods of the Integer and Double classes, which we have mentioned in passing. Therefore, they must be called using the name of the class, similar to Math.pow and Math.sqrt. returns an int returns a double 91

93 5.6 Canceling an Input Dialog Box So if we assume the user will enter a floating-point value for the radius, then the code needs to be the following: String inputStr = JOptionPane.showInputDialog(null, "Enter the radius", "0"); if (inputStr == null) return; double radius = Double.parseDouble(inputStr); So we get the number as a String, and then parse it to a double, and store it in a double variable. 92

94 5.6 Output Using showMessageDialog A convenient way to display output to a user, in a console or an applet program, is to use an output dialog box by calling the method showMessageDialog of the JOptionPane class: JOptionPane.showMessageDialog(null, "The area is " + area, "Output Window", JOptionPane.INFORMATION_MESSAGE ); required output message title bar label message icon Four parameters separated by commas INFORMATION_MESSAGE Icon 93

95 5.6 Output Using showMessageDialog We can display an output dialog box with an Error icon rather than an Information icon if we want to. To do this the last parameter changes: JOptionPane.showMessageDialog(null, "Error: Radius must be >= 0", "Output Window", JOptionPane.ERROR_MESSAGE); required output message title bar label message icon Four parameters separated by commas ERROR_MESSAGE Icon 94

96 5.6 CircleAreaDemo Program Code Here is some of the code of the CircleAreaDemo program: String inputStr = JOptionPane.showInputDialog(null, "Enter the radius", "0"); if (inputStr == null) return; double radius = Double.parseDouble(inputStr); if (radius < 0) JOptionPane.showMessageDialog(null, "Error: Radius must be >= 0", "Output Window", JOptionPane.ERROR_MESSAGE); else { double area = Math.PI * Math.pow(radius, 2); JOptionPane.showMessageDialog(null, "The area is " + area, "Output Window", JOptionPane.INFORMATION_MESSAGE); } 95

97 Chapter 5 Review When testing a loop, try running varying test data to make sure the loop processes all values correctly. Make sure you test the initial value of the loop and the loop limit value just before the loop stops to make sure they process everything correctly so you don’t have an OBO (Off-By-One error). If a loop produces errors, use debugging output statements to verify the values of the control variable on each pass through the loop. Branching statements, such as an if, if-else, and extended if statements, can be nested within loops to provide a powerful mechanism for solving problems. A break statement can be used with an if statement to terminate a while or for loop early. 96


Download ppt "Chapter 5 Loops, Printf Statements, Nested Control Statements and GUI Input & Output Section 1 - While Loops Section 2 - Printf Statements Section 3 -"

Similar presentations


Ads by Google