Download presentation
Presentation is loading. Please wait.
Published byLesley Merritt Modified over 9 years ago
1
Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing the list of statements in curly braces ({ }). The statements in side of the braces will be executed sequentially, and the block counts as one statement.
2
Compound Statement Example if (a > b) { c = a; System.out.println(a); } else { c = b; System.out.println(b); }
3
IF statement If there is nothing to do if the test is fals e, then the else part of the statement can be omitted, leaving just an IF statement: if (n > 0) n = n + 1;
4
Nested If statements If statements can be nested, that is, the statement to be done when the test is true (or false) can also be an If statement. Consider printing out three numbers in order:
5
An Extended Example if(a > b) if(b > c) System.out.println(a + " " + b + " " + c); else // b <= c if(a > c) System.out.println(a + " " + c + " " + b); else // a <= c System.out.println(c + " " + a + " " + b); else // a <= b if(a > c) System.out.println(b + " " + a + " " + c); else // a <= c...
6
Multi-way If-else Statement If the statement that is done when the test is false is also an If statement, it is customary to write the else and the if on one line: if(b > c) System.out.prinln(a + " " + b + " " + c); else if(a > c) is written if (b > c) System.out.print(a + " " + b + " " + c); else if (a > c)
7
More on Multi-way If Statements This is common when there are a number of possibilities based on the value of a variable: if (bedSoftness > 10) System.out.println("Too hard!"); else if(bedSoftness > 5) System.out.println("Just right!"); else System.out.println("Too soft!");
8
Dangling Else Problem Consider the following code: if (a > b) if (b > c) System.out.println(c); else System.out.println(b); Does the else go with if(a > b) or with if (b > c) ?
9
Answer It goes with the last if statement that is without an else, that, is if(b > c).
10
The Switch Statement If there are many cases the depend on the exact value of an int or char variable, rather than on ranges, we could use a multi-way if statement: if (class == 1) System.out.println("COSC 150"); else if (class == 2) System.out.println("COSC 160"); else if (class == 3) System.out.println("COSC 507");
11
The Switch Statement (cont'd) Or, we could use the switch statement, which implements multi-way branches based on the value of an expression. switch (class) { case 1: System.out.println("COSC 150"); break; case 2: System.out.println("COSC 160"); break; case 3: System.out.println("COSC 507"); break; default: System.out.println("Illegal value"); break; }
12
The Switch statement (cont'd) What the switch statement does depends on the controlling expression, given in parentheses. If the value matches one of the cases, that code is done. Without the break statement, the next case is also done. The break statement forces the program to bypass the rest of the cases. The default case is done if the value doesn't match any of the cases.
13
The Break Statement The use (or non-use) of the break statement gives the programming greater flexibility. You decide if the next case is to be done or not. The reason you might want the next case to be done is that often different values should be processed the same way: switch (inputCommand) { case 'A': case 'a': System.out.println("command a"); break; case 'C': case 'c': System.out.println("command c"); break; }
14
Multi-way If vs. Switch The switch statement is more compact than the multi-way if statement and should be used when the code to be done is based on the value of an int or char expression. However, the switch statement cannot be floating point expressions and so the multi-way if statement must be used. The switch statement may be used for strings in Java SE 7 and later.
15
Enumerated Types Often, a problem uses a set of named literals (constants), e.g., the months of the year, or the days of the week. Good programming practice says that we should use mnemonic names rather that numbers to represent such items. Instead of creating twelve (or seven) constants, we can use an enumerated type – that is create a set of new literals to represent the items.
16
Enumerated Type Examples public enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEPT, OCT, NOV, DEC }; public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
17
Using an Enumerated Type Enumerated types can be used with the Switch statement: Month m; switch (m) { case JAN: break; case FEB: break;... case DEC: break; }
18
The Conditional Operator The conditional operator (my personal favorite of all the operators) is a trinary operator (three operands) which evaluates a test (Boolean expression) and based on the value of the expression, takes its value from one of two other expressions (the true-case value or the false-case value). It is similar to an if- else statement, but can be used in an expression.
19
Conditional Operator Example System.out.println(a > b ? a : b); is more succinct than the if-else statement if (a > b) System.out.println(a); else System.out.println(b);
20
Reading in a char via Scanner The Scanner class has a nextInt() method, and a nextDouble() method, but no nextChar() method. To read in a character, you must read in a String (using the next() method) and then extract the first character. The code is: char c = sc.next().charAt(0);
21
Exercise Write a Java program that reads in a char from the user and then a number (double). If the char is 'C' or 'c', then the number is the radius of a circle. If the char is 'S' or 's', then the number is the side of a square. If the letter is 'G' or 'g' then the number is the radius of a sphere. The program should then print out the area of the object.
22
Exercise (cont'd) Your program should: Read in a char shape Read in a double d Use a multi-way if statement or a switch statement to distinguish the choices Calculate the area (vol) of the object and print it out Circle = PI * d 2 ; Square == d 2 ; Sphere: 4/3 * PI * d 3
23
Loops Use to repeat steps Different kinds: Count-controlled: when you know ahead of time how many times to loop Sentinel-controlled: when reading until a special value General Condition: Arbitrary loop Three Java statements to implement loops: while, do-while, and for.
24
Count-Controlled Loops If you know the number of times you want to repeat a section of code, you can use a count-controlled loop. A for-statement is usually used. The syntax is: for(int i = 0; i < 10; i++) Note the use of semicolons to separate the parts of the for statement. If the loop body is more than one statement, braces may be used.
25
Anatomy of a For Statement Here is a close-up of the For statement: int i = 0; // initialization i < 10; // test i++ // increment The variable i is the loop index. First it is initialized to 0. Then before the loop body is executed, the test is checked. If the test evaluates to true the loop body is executed and the increment is done.
26
Anatomy of a For Statem't (cont'd) If the test evaluates to the false, the loop is done, and the program continues with the next line following the loop. Note: The loop index is only valid inside of the loop. Once the loop is finished, that i becomes meaningless.
27
Syntax The syntax of a For statement is: for( ; ; ) Any of the the parts may be omitted. For example, for(;;) is an infinite loop.
28
Example for (int i=0; i<10; i++) System.out.println(i + "^2 = " + i*i); would print out: 0^2 = 0 1^2 = 1 2^2 = 4 3^2 = 9 4^2 = 16 5^2 = 25 6^2 = 36 7^2 = 49 8^2 = 64 9^2 = 81
29
Note on Example The index of loop goes from 0 to 9, inclusive, and not from 0 to 10. It is a Java idiom to begin loops at 0, since arrays start at 0. Thus to repeat code ten times, the test is “i < 10” and not “i <= 10.”
30
Potential Pitfall It is a bad idea to change the value of the loop index inside of the loop. For example, for (int i=0; i<10; i++) { System.out.println(i + "^2 = " + i*i); i++; } would print out: 0^2 = 0 2^2 = 4 4^2 = 16 6^2 = 36 8^2 = 64
31
Potential Pitfall (cont'd) In this case, it would be better to use a different increment step, e.g., i = i + 2. Another case where programmers change the index variable is to jump out the loop prematurely, e.g., set i to 10. It is better to use the break statement to jump out of the loop this way.
32
Break, Continue, and Return The break statement can be used to jump out of a loop prematurely. Control passes to the statement following the loop. The continue statement will cause the program to skip over any remaining part of the loop body and begin the next iteration of the loop. The return statement will exit the method that the loop is in.
33
Example int a = 5, b = 7; for (int i=0; i<10; i++) { a = a * b; if(a > 1000) // too big break; } System.out.println(a);
34
Nested Loops Loops, including For statements, may be nested, that is, one loop is included in the loop body of another loop. This is useful for processing 2-dimensional tables. The loop indices must be different variables.
35
Example for(int i=1; i<= 10; i++) { for(int j=1; j<= 10; j++) System.out.printf( " %3d", i * j); System.out.println(); } will print out the multiplication table.
36
Exercise Write a loop that will read in 25 numbers (ints) and will print out the smallest number read in.
37
While Statement In addition to the For statement, Java contains the While statement, which allows code to be repeated while an arbitrary condition holds. For example: while(a < b) a *= 2; is a while loop. The loop continues as long as a is less than b, and halts when a becomes greater than or equal to b.
38
Using a While for a For A While statement could be used instead of a For statement. The For statement: for(int i=0; i<25; i++) could be re-written as: int i = 0; while(i < 25) { i++; }
39
Sentinel Controlled Loop A sentinel-controlled loop reads values until a special value (the sentinel) is read, which cannot be a valid. For example, if the program is reading in grades, then a negative number could be used for the sentinel, as it is not a valid grade.
40
Example total = 0; grade = sc.nextInt(); while(grade >= 0) { total += grade; grade = sc.nextInt(); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.