compound statements if you want to do more than one statement if an if- else case, you can form a...

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

Upload: lesley-merritt

Post on 03-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 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

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.

Page 2: 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

Compound Statement Example

if (a > b) { c = a; System.out.println(a);}else { c = b; System.out.println(b);}

Page 3: 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

IF statement

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;

Page 4: 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

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:

Page 5: 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

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

Page 6: 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

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)

Page 7: 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

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!");

Page 8: 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

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)?

Page 9: 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

Answer

It goes with the last if statement that is without an

else, that, is if(b > c).

Page 10: 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 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");

Page 11: 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 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;

}

Page 12: 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 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.

Page 13: 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 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;

}

Page 14: 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

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.

Page 15: 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

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.

Page 16: 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

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 };

Page 17: 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

Using an Enumerated Type

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;

}

Page 18: 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 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.

Page 19: 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

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

Page 20: 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

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

Page 21: 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

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.

Page 22: 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

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 choicesCalculate the area (vol) of the object and print it out

Circle = PI * d2; Square == d2; Sphere: 4/3 * PI * d3

Page 23: 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

Loops

Use to repeat stepsDifferent 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 loopThree Java statements to implement loops: while, do-while, and for.

Page 24: 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

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++) <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.

Page 25: 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

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.

Page 26: 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

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.

Page 27: 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

Syntax

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.

Page 28: 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

Examplefor (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

Page 29: 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

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

Page 30: 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

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

Page 31: 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

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.

Page 32: 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

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.

Page 33: 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

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

Page 34: 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

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.

Page 35: 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

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.

Page 36: 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

Exercise

Write a loop that will read in 25 numbers (ints) and

will print out the smallest number read in.

Page 37: 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

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.

Page 38: 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

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++)

<loop body>

could be re-written as:int i = 0;

while(i < 25) {

<loop body>

i++;

}

Page 39: 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

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.

Page 40: 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

Example

total = 0;

grade = sc.nextInt();

while(grade >= 0) {

total += grade;

grade = sc.nextInt();

}