98
Chapter 5 Loops Section 1 - While Loops Section 2 - For Loops Section 3 - printf Statements Section 4 - Loop Errors Section 5 - Nested Control Statements & Loop Errors Section 6 - Input & Output GUI Dialog Boxes Go Go Go Go Go Go

Chapter 5 Loops Section 1 - While Loops Section 2 - For Loops Section 3 - printf Statements Section 4 - Loop Errors Section 5 - Nested Control Statements

Embed Size (px)

Citation preview

Chapter 5Loops

Section 1 - While Loops

Section 2 - For Loops

Section 3 - printf Statements

Section 4 - Loop Errors

Section 5 - Nested Control Statements & Loop Errors

Section 6 - Input & Output GUI Dialog BoxesGo

Go

Go

Go

Go

Go

Chapter 5 Section 1

While Loops

3

5.1 What are Control Statements?We call ….

if statements

if-else statements

while loops

and for loops

control statements

because they control the order of execution in a Java program.

4

5.1 Definition of a While LoopIn Java you can execute a segment of code over and over again

while a boolean condition evaluates to true. When the boolean condition 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).

A while loop looks like this:

while (some boolean condition is true)

{

<execute these lines of code inside the loop body>

}

No code is executed if the boolean condition is initially false. The loop is skipped!

5

5.1 A Count Up while Loop ExampleA 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.

6

5.1 Tracing a Count Up while LoopIt 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;int cntr = 1; 1while (cntr <= 3) 2 5 8

{sum += cntr; 3 6 9

cntr++; 4 7 10

}System.out.println(sum); 11

The blue numbers indicate the order the lines of code are executed in.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

5.1 Skeleton of a Count Up while LoopIf 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

5.1 General Form of a while loopThe while loop executes statements inside its body repeatedly for as long as its 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) { // saves lines by putting { on same line of conditions

tatement;

statement;

} No semicolon goes here!

while (condition) No semicolon goes here!{ // adds readability by putting curly brace { on separate line

statement;

statement;

}

No curly braces required for just one line of code in the loop.

9

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.

10

5.1 Count Down while Loops

Countdown Loop code:

int sum = 0;int cntr = 100;while(cntr >= 1){

sum += cntr;

cntr--;

}

Note the code in the loop is exactly the same. Only the loop header and the initiaization value of the lcv have been changed. 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++;

}

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.

12

5.1 A Count-Down While Loop ExampleYou 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.0The square root of 20 is 4.47213595499958The square root of 15 is 3.872983346207417The square root of 10 is 3.1622776601683795

13

5.1 A Count-Down While Loop ExampleWhat 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.0The square root of 20 is 4.47213595499958The square root of 15 is 3.872983346207417

14

5.1 Calculating a Factorial Example

System.out.print("Enter a number greater than zero: ");int number = reader.nextInt();

int product = 1;

int cntr = 1;

while (cntr <= number)

{

product *= cntr;

cntr++;

}

System.out.print("The factorial of " + number);

System.out.println(" is " + product);

The variable number can be referred to as the upper limit of the loop.

15

5.1 Task-Controlled While LoopsA 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.

16

5.1 Interesting While Loop ExampleCode 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.

17

5.1 User-Controlled While Loop ExampleThe 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);

18

5.1 Order & Structure of a While Loop

1) Initialize the loop control variable and other variables.

2) Test 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 and other variables.

4) When the condition becomes false, the loop stops without executing the body.

initialize loop control variable // initialize

while (condition) // test the condition

{ // execute the body of loop

perform calculations and

change variables involved in the condition

}

19

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

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 < 0 || 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

20

21

5.1 Flow Chart for The while Statement

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.

Chapter 5 Section 2

For Loops

23

5.2 Definition of a For LoopIn 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) {

<lines of code inside the loop body>}

Here 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.

24

5.2 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.

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.

25

5.2 The for Loop Order of ExecutionIt 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

26

5.2 A Second While & For Loop ComparisonCompare 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);

Any code you can write using a for loop can be written also using a while loop and vice versa. For loops provide an efficient way to write quickly a loop header that has all of the requirements of a loop and this can 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.

27

5.1 Skeleton of a Count Up for LoopIf 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.

28

5.2 A User-Controlled for LoopWe have already seen the following approach used with a while loop. Here is a similar version that uses a for

loop.

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;

for(int cntr = startingValue; cntr <= endingValue; cntr ++)

{

s

u

m

+

=

c

n

t

r

;

}

System.out.println("The sum is: " + sum);

29

5.2 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 <=. You could use > instead of < also.

30

5.2 Count-Controlled Input with a for LoopThis 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 sum = 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();

sum += number;

}

Note: the letter i has long been used as a lcv. This is a tradition that has continued over the years with programmers.

31

5.2 Declaring a For Loops Control Variable

It is possible to declare a for loop’s loop control variable (lcv) outside of the for loop header. However, possible program side-effects can occur with that variable if it is used after the loop in another segment of code. So if you declare the lcv outside the loop header for some reason, be careful and be sure and reinitialize if you use it in another loop.

int i; // i declared before header

for ( i = 1; i <= 10; i++)

{

System.out.println(i);

}

// not the preferred way to write it but ok if you need to use i outside the loop.

// i declared inside header

for (int i = 1; i <= 10; i++)

{

System.out.println(i);

}

// preferred way to write it if you don’t need to use i outside of the loop.

32

5.2 Declaring the LCV inside the Header

In conclusion, generally, it is better to declare the loop control variable within the loop header for two reasons:

1. The variable i is only visible within the loop. This is a good thing. No side-effects.

for (int i = 1; i <= 10; i++)

System.out.println(i);

i++;

So if you try to write i++; outside the loop, Eclipse will complain that it doesn’t know i. This is because i was declared in the loop header and it is only available or known inside the loop … not outside.

33

5.2 Declaring the LCV inside the Header

2. If declared inside the loop header, the variable i can be reused later in other loops as the lcv without a side effect, even though it could be reset to one if it wasn’t declared inside the loop.

for (int i = 1; i <= 10; i++)

System.out.println(i);

for (int i = 1; i <= 25; i++)

System.out.println(i);

One of the reasons for declaring the lcv inside the for loop header is that programmers traditionally like to use i as a loop control variable. In early programming languages, you wanted all of your code to be as short as possible, so if you needed different loop control variable names for different loops, then you used variables i, j, and k.

Two different loops that both use i as the lcv.

34

5.2 Declaring the LCV Outside the Header

However, you could still declare the lcv outside of the loop and

use it in more than one loop, if you understand that i needs

to be reset to one before it is used again. This is approach

is used below in both for loop headers.

int i;

for (i = 1; i <= 10; i++)System.out.println(i);

for (i = 1; i <= 25; i++)System.out.println(i);

35

5.2 for Loops or while Loops?Both for loops and while loops are called entry-controlled

loops, because the loop test condition is tested at top of the loop before the loop body is entered the first time and before each iteration.

Choosing a for loop versus a while loop is often a matter of

style, but a for loop has several advantages:

• Can declare loop control variable in header

• Initialization, condition, and update in one line of code

• It is easy to see if you have everything you need to run

the loop. It can be easy to overlook initializing all of the

variables needed before executing a while loop. And it

is easy to forget to update the loop control variable for a

while loop. Many programmers forget to include cntr++.

36

5.2 Flow Chart for The for Loop

Notice the return arrow after the last statement in the loop. It makes contact above the condition diamond.

The flow chart for a for loop is the same as the flow chart for a while loop.

Chapter 5 Section 3

Formatting Console Output

with printf statements

38

5.3 Introduction to printf statementsprint and println statements don’t allow us to easily format output to

the screen or a file. 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 do this and to print items 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 output in columns. This makes the output more readable to the user of a program.

Freezing = 3 2Boiling = 2 1 2Fiery = 5 1 3 4Nice = 8 7Super Hot = 6 9 2 4 1

The words are left justified.

The integers are right justified.

39

5.3 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 a String value.

Format specifiers always begin with the % symbol.

40

5.3 printf Statement Examples

Here are three examples of printf statements.

System.out.println has been replaced with System.out.printf.

System.out.printf ("%7d”, fahrenheit);

System.out.printf ("%10.4f”, percentage );

System.out.printf ("%20s”, phrase);

Here fahrenheit is an int variable, percentage is a double variable, and phrase is a String variable. We’ll explain what is in the ( ) of a System.out.printf statement next.

41

5.3 The printf Format SpecifiersThere are three primary format specifiers that we will

use:

the letter d for decimal (base-10) int values as in %5d

the letter f for decimal floating point values as in %8.2f

the letter s for string values as in %10s

Also %n tells Java to display a new-line character, but you can also use the escape sequence \n in its place.

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 right justified. The - is called a format flag. You’ll see examples coming up.

42

5.3 The Format Specifier for intprintf 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). 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. 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 the following:

_ _ _ _ 212

The printf statement right justifies the value stored in the variable fahrenheit in a field width of 7 spaces.

43

5.3 The Format Specifier for int

We can also add other string information inside the format string that we want printed out prior to 212:

int fahrenheit = 212;System.out.printf(“Temperature = %7d”, 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). 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

44

5.3 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.

45

5.3 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 FahrenheitTemperature = _ _ _ _ 2 1 2 FahrenheitTemperature = _ _ _ 5 1 3 4 FahrenheitTemperature = _ _ _ _ _ 8 7 FahrenheitTemperature = _ _ 6 9 2 4 1 Fahrenheit

46

5.3 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 and then the formatting would be off on that one

line as seen below.

Temperature = _ _ _ _ _ 3 2 FahrenheitTemperature = _ _ _ _ 2 1 2 FahrenheitTemperature = _ _ _ 5 1 3 4 FahrenheitTemperature = _ _ _ _ _ 8 7 FahrenheitTemperature = 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.

47

5.3 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

48

5.3 Left Justification for intYou 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 10 spaces.

49

5.3 The Format Specifier for doubleprintf 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

50

5.3 Left Justification for doubleWe 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 _ _ _

51

5.3 The Format Specifier for Stringprintf 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. 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 !

52

5.3 Left Justification for StringsIn 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 ! _ _ _ _ _ _ _

53

5.3 The New Line Format SpecifierNone 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 must be 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 like it does with other format specifiers.

Notice there doesn’t need to be a space between any two format specifiers.

54

5.3 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);

55

5.3 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.

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!

56

5.3 Multiple Format Specifiers in One LineSometimes 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:

for (int i = ?: ???; ???){

double square = ???;double cube = ???;

System.out.printf("The square of %5.1f is %6.1f and the cube is %7.1f%n", i, square, cube);

}The output all on one line would look something like this:

The square of 1.0 is 1.0 and the cube is 1.0The square of 2.0 is 4.0 and the cube is 8.0The square of 3.0 is 9.0 and the cube is 27.0The square of 4.0 is 16.0 and the cube is 64.0The square of 5.0 is 25.0 and the cube is 125.0

57

5.3 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.0The square of 2.0 is 4.0 and the cube is 8.0The square of 3.0 is 9.0 and the cube is 27.0The square of 4.0 is 16.0 and the cube is 64.0The square of 5.0 is 25.0 and the cube is 125.0

58

5.3 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 string information.

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 three 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);

59

5.3 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 Perfect Number is %,30d", num);

This gives the output:

The 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.

Chapter 5 Section 4

Loop Errors

61

5.4 The Four Components of Loops

A loop usually has four component parts:• initializing statements• terminating conditions• body statements• update statements

Many errors with loops occur because the programmer introduces a logic error into any one of these components.

62

5.4 A Correctly Coded Loop Example

// Computes the product of the odd integers from 1 to 100

int product = 1;

int i = 3;

while ( i <= 100 )

{

product *= i;

i += 2;

}

System.out.println(product);

63

5.4 Loop Errors are Usually Logic Errors

The following slides contain loop errors. The code will compile and run but they will give incorrect output because they have logic errors.

The intent of the code on the following slides is to print out the product of 3 * 5 * 7 * … * 97 * 99.

64

5.4 Loop Initialization Error

Because the variable product is not initialized below, this is called an initialization error.

int product; // not initialized to 1int i = 3;

while ( i <= 100 ){

product *= i;i += 2;

}System.out.println(product);

65

5.4 Loop Off-By-One ErrorBecause 99 is the upper limit of the loop but i < 99 is used

instead of i <= 99, then the number 99 will not be used in the calculation of the product.

This is called an Off-By-One error or as we like to say an OBO.int product = 1;int i = 3;

while ( i < 99 ) // incorrect upper limit … use <= 99 instead{ // or you could use < 100 or <= 100

product *= i;i += 2;

}System.out.println(product);

66

5.4 Infinite Loop ErrorBecause the loop control variable i never equals exactly 100, an

infinite loop will occur. This is called an infinite loop error.

int product = 1;

int i = 3;

while ( i != 100 ) // i never equals 100

{

product *= i;

i += 2;

}

System.out.println(product);

67

5.4 Loop Body Error Because the line of code: product += i; doesn’t produce the

intended result, a logic error occurs. This is called a loop body error.

int product = 1;int i = 3;

while ( i <= 100 ){ // incorrect extended assignment

operatorproduct += i; // it should be *=i += 2;

}System.out.println(product);

68

5.4 Loop Update Error

Because the line of code: i += 2; is located in the wrong place, we have what is called a loop update error.

int product = 1;

int i = 3;

while ( i <= 100 )

{

i += 2; // bad location of update statement … swap with next line

product *= i;

}

System.out.println(product);

Chapter 5 Section 5

Nested Control Statements

70

5.5 Nested Control StatementsControl 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 100 is even or odd.

for (int cntr = 1; cntr <= 100; cntr++)

{

if (cntr % 2 == 0)

System.out.println(cntr + “ is even”);

else

System.out.println(cntr + “ is odd”);

}

71

5.5 Nested Control StatementsWe could also use …

for (int cntr = 1; cntr <= 100; cntr++)

{

if (cntr % 2 == 0)

System.out.println(cntr + “ is even”);

else if (cntr % 2 == 1)

System.out.println(cntr + “ is odd”);

}

72

5.5 Nested Control StatementsThe following code prints whether each integer between 1 and

100 is evenly divisible by some value, but there is a bug!

for (int cntr = 1; cntr <= 100; cntr++)

{

if (cntr % 3 == 0)

System.out.println(cntr + “ is evenly divisible by 3”);

else if (cntr % 4 == 0)

System.out.println(cntr + “ is evenly divisible by 4”);

else if (cntr % 5 == 0)

System.out.println(cntr + “ is evenly divisible by 5”);

}

What is the logic error in this code?

5.5 Nested Control Statementsfor (int cntr = 1; cntr <= 100; cntr++)

{

if (cntr % 3 == 0)

System.out.println(cntr + “ is evenly divisible by 3”);

else if (cntr % 4 == 0)

System.out.println(cntr + “ is evenly divisible by 4”);

else if (cntr % 5 == 0)

System.out.println(cntr + “ is evenly divisible by 5”);

}

Is 12 evenly divisible by 3 and 4?

Is 15 evenly divisible by 3 and 5?

How could this be resolved so the program would print that 12 is evenly divisible by 3 and 4, and 15 is evenly divisible by 3 and 5?

5.5 Nested Control Statements

The easiest solution is to replace the extended if statement by individual if statements so all true statements are printed.

for (int cntr = 1; cntr <= 100; cntr ++)

{

if (cntr % 3 == 0) System.out.println(cntr + “ is evenly divisible by 3”);

if (cntr % 4 == 0)

System.out.println(cntr + “ is evenly divisible by 4”);

if (cntr % 5 == 0)

System.out.println(cntr + “ is evenly divisible by 5”);

}

75

5.5 Nested Control StatementsAs we have said, almost every programming problem can be solved with the

combination of loops and control statements. The following code prints the proper divisors of an integer. A proper divisor is one that divides evenly into another integer.

System.out.print(“Enter a positive integer: ”);

int n = reader.nextInt();

int limit = n / 2; // why don’t we have to check above n / 2 ???

for (int d = 2; d <= limit; d++)

{

if (n % d == 0)

System.out.print(d + “ ”);

}

Are there ever any proper divisors of n greater than n / 2?

76

5.5 Nested Control StatementsAre there ever any proper divisors of n greater than n / 2?

Consider the number 15. The proper divisors are 1, 3, and 5. There are no proper divisors greater than 15 / 2 = 7.5

So using limit = n / 2 is a more efficient way to find the proper divisors of an integer.

System.out.print(“Enter a positive integer: ”);

int n = reader.nextInt();

int limit = n / 2;

for (int d = 2; d <= limit; d++)

{

if (n % d == 0)

System.out.print(d + “ ”);

}

Now we ask the question:

“Are there any proper divisors greater than the square root of n?”

77

5.5 Nested Control Statements“Are there any proper divisors greater than the square root of n?”

Consider the number 15. The proper divisors are 1, 3, and 5. There is one proper divisor (5) greater than √15 = 3.873. However, we can find it because it must have a corresponding factor less than the √15, in other words 3.

So using limit = (int) Math.sqrt(n) can be an even more efficient way to find the proper divisors of an integer. If we stop and calculate the corresponding factor of every proper divisor less than the √n. This is very helpful when n is very large.

System.out.print(“Enter a positive integer: ”);int n = reader.nextInt();int limit = (int) Math.sqrt(n);for (int d = 2; d <= limit; d++){

if (n % d == 0){

System.out.println(d + “ is a proper divisor.”);System.out.println(n/d + “ is a proper divisor.”);

}}

78

5.5 Nested Control StatementsThink of it mathematically this way using a number line:

0 √n n / 2 n

√15 15 / 2

3.873 7.5

15

Just think about if n is 1,000,000 and you are finding all the proper divisors, you only have to go up to 1,000, since the √1,000,000 is 1,000. There are 999,000 numbers you don’t have to check!

only check this range

no need to check this entire range

79

5.5 The break Statements in For LoopsBreak statements may be used in while and for loops, not just while (true) loops. In the code below when a proper divisor is found the loop halts because of the break statement and the variable prime will get the correct value of false. Notice our code assumes n is prime until proven false.

System.out.print(“Enter an integer greater than 2: ”);

int n = reader.nextInt();int limit = n / 2;boolean prime = true;

for (int d = 2; d <= limit; d++){ if (n % d == 0) {

System.out.println(d + " is a factor of " + n);prime = false;break;

}}if (prime) System.out.println(n + " is prime." );else System.out.println(n + " is NOT prime." );

A fairly good efficient way of trying to see if a number is prime.

80

5.5 The break Statements in For LoopsThis is the same code as the previous slide except for the line in red, which uses the square root of n to calculate the upper limit of the loop.

System.out.print(“Enter an integer greater than 2: ”);

int n = reader.nextInt();int limit = (int) Math.sqrt(n);boolean prime = true;

for (int d = 2; d <= limit; d++){ if (n % d == 0) {

System.out.println(d + " is a factor of " + n);prime = false;break;

}}if (prime) System.out.println(n + " is prime." );else System.out.println(n + " is NOT prime." );

A more efficient way of trying to see if a number is prime.

81

5.5 Sentinel-Controlled InputIn the following code that we saw when we first talked about while loops, -1 is a sentinel value because it makes the loop 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

}

82

5.5 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 and it is being converted to binary along the way and then back to base-10. In 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.

83

5.5 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 leads 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!

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 …

84

5.5 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.0999999999999999etc.

85

5.5 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

Chapter 5 Section 6

Input & Output GUI Dialog Boxes

87

5.6 The JOptionPane ClassThe 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

5.6 Receiving Input Using showInputDialogA 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");

“Enter the radius” is the prompt and a default value of zero appears in the text entry field. The user can use the default value or enter something else and then click OK.

89

5.6 Cancelling an Input Dialog BoxWhen 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:

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

5.6 Parsing Numeric InputAll 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 …

I

n

t

e

g

e

r

.

p

a

r

s

e

I

n

t

(

)

o

r

D

o

u

b

l

e

.

p

a

r

s

e

D

o

u

b

l

e

(

)

These methods convert the input String value to an int or double 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

5.6 Cancelling 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,

parse it to a double,

and store it in a

double variable.

92

5.6 Output Using showMessageDialogA convenient way to display output to a user, even in a console

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

5.6 Output Using showMessageDialogWe can display an output dialog box with an Error icon rather than an

Information icon if we wan 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

5.6 CircleArea_5_2 Program CodeHere is some of the code of the CircleArea_5_2 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

5.6 The setPreferredSize() methodIn graphics programs that use JPanels, we can set up multiple

panels by using a loop to initialize and insert the panels.

We can set the preferred size of a panel by using JPanel class’s setPreferredSize() method. This will ensure that the panels will be constructed using our chosen size. However, if we have so many panels that the screen can’t display them at that size, then Java will resize them all so that they all can be displayed.

We would use the following line in a ColorPanel class constructor to allow Java to use the size of the panel we want:

setPreferredSize( new Dimension (width, height) );

96

5.6 setPreferredSize() Code Example

public class ColorPanel_5_4 extends JPanel{ // Client provides color and preferred width and height public ColorPanel_5_4(Color backColor, int width, int height) { setBackground(backColor); setPreferredSize(new Dimension(width, height)); }

// Client provides color // Preferred width and height are 0, 0 by default public ColorPanel_5_4(Color backColor) { setBackground(backColor); }}

97

5.6 pack() vs setSize()

JFrame class’s pack() method will cause the window to adjust its size to exactly fit the preferred size of any contained panels. If you use the setSize () method instead, then you may have extra blank space in your window next to the panels. The pack() method will eliminate the extra blank space.

Therefore, if you use pack(), there is no reason to use setSize() to set the size of the window. We can control the size of each panel with the ColorPanel constructor and then the window will enlarge itself to accommodate all of the panels. But again if we have too many panels, their size will be reduced by Java so they all fit on the screen.

98

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.

• 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.