410 likes | 531 Views
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.
E N D
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. Compound Statements
if (a > b) { c = a; System.out.println(a); } else { c = b; System.out.println(b); } Compound Statement Example
If there is nothing to do if the test is false, then the else part of the statement can be omitted, leaving just an IF statement: if (n > 0) n = n + 1; IF statement
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: Nested If statements
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 ... An Extended Example
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) Multi-way If-else Statement
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!"); More on Multi-way If Statements
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)? Dangling Else Problem
It goes with the last if statement that is without an else, that, is if(b > c). Answer
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"); The Switch Statement
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; } 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. The Switch statement (cont'd)
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; } The Break Statement
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. Multi-way If vs. Switch
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. Enumerated Types
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 }; Enumerated Type Examples
Enumerated types can be used with the Switch statement: Month m; switch (m) { case JAN: <code> break; case FEB: <code> break; ... case DEC: <code> break; } Using an Enumerated Type
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. The Conditional Operator
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); Conditional Operator Example
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); Reading in a char via Scanner
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. Exercise
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 * d2; Square == d2; Sphere: 4/3 * PI * d3 Exercise (cont'd)
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. 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++) <loop body> 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. Count-Controlled Loops
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. Anatomy of a For Statement
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. Anatomy of a For Statem't (cont'd)
The syntax of a For statement is: for(<initialization>; <test>; <increment>) <loop body> Any of the the parts may be omitted. For example, for(;;) <loop body> is an infinite loop. Syntax
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 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.” Note on Example
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 Potential Pitfall
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. Potential Pitfall (cont'd)
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. Break, Continue, and Return
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); Example
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. Nested Loops
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. Example
Write a loop that will read in 25 numbers (ints) and will print out the smallest number read in. Exercise
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. While Statement
A While statement could be used instead of a For statement. The For statement: for(int i=0; i<25; i++) <loop body> could be re-written as: int i = 0; while(i < 25) { <loop body> i++; } Using a While for a For
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. Sentinel Controlled Loop
total = 0; grade = sc.nextInt(); while(grade >= 0) { total += grade; grade = sc.nextInt(); } Example