12/10/2022
JAVA PROGRAMMING
Week 2: Program Control
Statements
Lecturer: NGUYỄN Thị Minh Tuyền
Plan 2
1. Input characters from the keyboard
2. The if statement
3. The switch statement
4. The complete form of the for loop
5. The while loop
6. The dowhile loop
7. Use break to exit a loop
8. Use break as a form of goto
9. Apply continue
10. Nest loops
Java Programming
1
12/10/2022
Input characters from the
keyboard 3
• To read a character from the keyboard, we will use
System.in.read().
• System.in is the complement to System.out.
• The read() method waits until the user presses a key
and then returns the result.
• The character is returned as an integer, so it must be cast
into a char to assign it to a char variable.
• By default: console input is line buffered. The buffer holds
a complete line of text à the program waits for ENTER
pressed by the user.
Java Programming
Example 4
1. // Read a character from the keyboard.
2. public class KbIn {
3. public static void main(String[] args)
4. throws java.io.IOException{
5. char ch;
6.
7. System.out.print("Press a key followed by ENTER: ");
8. ch = (char) System.in.read(); // get a char
9. System.out.println("Your key is: " + ch);
10. }
11. }
Java Programming
2
12/10/2022
if statement [1] 5
if(condition)
statement;
else
statement;
• The targets of the if and else are single statements.
• The else clause is optional.
• The targets of both the if and else can be blocks of
statements.
Java Programming
if statement [2] 6
1. if(condition)
2. {
3. statement sequence
4. }
5. else
6. {
7. statement sequence
8. }
Java Programming
3
12/10/2022
Example: Guess a letter (V1) 7
1. // Guess the letter game.
2. public class Guess {
3. public static void main(String[] args)
4. throws java.io.IOException{
5.
6. char ch, answer = 'K';
7. System.out.println("I'm thinking of a letter
8. between A and Z.");
9. System.out.print("Can you guess it: ");
10. // read a char from the keyboard
11. ch = (char)System.in.read();
12. if(ch == answer) System.out.println("** Right **");
13. }
14. }
Java Programming
Example: Guess a letter (V2) 8
1. // Guess the letter game.
public class Guess2 {
2.
public static void main(String[] args)
3.
throws java.io.IOException{
4. char ch, answer = 'K';
5. System.out.println("I'm thinking of a letter
6. between A and Z.");
System.out.print("Can you guess it: ");
7.
// read a char from the keyboard
8.
ch = (char)System.in.read();
9. if(ch == answer) System.out.println("** Right **");
10. else System.out.println("...Sorry, you're wrong.");
}
11.
}
12.
13.
Java Programming
14.
4
12/10/2022
Nested ifs 9
• A nested if is an if statement that is the target of
another if or else.
• Nested ifs are very common in programming.
• Main thing to remember: an else statement always
refers to the nearest if statement that is within the same
block as the else and not already associated with an
else.
if(i == 10) {
if (j < 20) a = b;
if (k > 100) c = d;
else a = c; // this else refers to if(k > 100)
}
else a = d; // this else refers to if(i == 100)
Java Programming
1. // Guess the letter game.
public class Guess3 {
10
2.
3. public static void main(String[] args)
4. throws java.io.IOException{
5. char ch, answer = 'K';
6. System.out.println("I'm thinking of a letter between A
7. and Z.");
8. System.out.print("Can you guess it: ");
9. ch = (char)System.in.read();
10. if(ch == answer) System.out.println("** Right **");
11. else {
12. System.out.print("...Sorry, you're ");
13. // a nested if
14. if (ch < answer) System.out.println("too low");
15. else System.out.println("too high");
16. }
17. }
18. } Java Programming
10
5
12/10/2022
The if-else-if ladder 11
1. if(condition)
2.
statement;
3.
else if(condition)
4.
statement;
5.
else if(condition)
6.
statement;
7.
.
8.
9.
.
10.
.
11. else
12. statement;
Java Programming
11
1. // Demonstrate an if-else-if ladder.
2. public class Ladder { 12
3. public static void main(String[] args) {
4. int x;
5. for(x = 0; x < 6; x++) {
6. if(x == 1)
7. System.out.println("x is one");
8. else if(x == 2)
9. System.out.println("x is two");
10. else if(x == 3)
11. System.out.println("x is three");
12. else if(x == 4)
13. System.out.println("x is four");
14. else // this is the default statement
15. System.out.println("x is not between 1 and 4");
16. }
17. }
18. } Java Programming
12
6
12/10/2022
The switch statement 13
1. switch(expression) {
2. case constant1: Prior to JDK 7:
3.
The expression controlling the
statement sequence switch must resolve to type byte,
4. break; short, int, char, or an enumeration.
5. From JDK 7:
case constant2:
6. Expression can also be of type
statement sequence String.
7.
break;
8.
case constant3:
9.
statement sequence
10.
break;
11.
12. ...
13.
default:
14. statement sequence
Java Programming
15. }
13
1. // Demonstrate the switch
2. public class SwitchDemo {
public static void main(String[] args) {
14
3.
int i;
4.
for(i=0; i<10; i++)
5.
switch(i) {
6.
case 0:
7. System.out.println(i + " is zero"); break;
8. case 1:
9. System.out.println(i + " is one"); break;
case 2:
10.
System.out.println(i + " is two"); break;
11. case 3:
12. System.out.println(i + " is three"); break;
13. case 4:
14.
System.out.println(i + " is four"); break;
default:
15.
System.out.println(i + " is five or more");
16. }
17. }
18. } Java Programming
14
7
12/10/2022
1. // Demonstrate the switch without break statements
2. public class NoBreak {
3. public static void main(String[] args) { 15
4. int i;
5. for(i=0; i<5; i++)
6. switch(i) {
7. case 0:
8. System.out.println(i + " is zero");
9. case 1:
10. System.out.println(i + " is one");
11. case 2:
12. System.out.println(i + " is two");
13. case 3:
14. System.out.println(i + " is three");
15. case 4:
16. System.out.println(i + " is four");
17. default:
18. System.out.println(i + " is five or more");
19. }
20. }
21. }
Java Programming
15
16
1. switch(i) {
2. case 1:
3. case 2:
4. case 3: System.out.println("i is 1, 2 or 3");
5. break;
6. case 4: System.out.println("i is 4");
7. break;
8. }
Java Programming
16
8
12/10/2022
Nested switch statements 17
• It is possible to have a switch as part of the statement sequence
of an outer switch. This is called a nested switch.
switch(ch1) {
case 'A’:
System.out.println("This A is part of outer switch.");
switch(ch2) {
case 'A’:
System.out.println("This A is part of inner
switch");
break;
case 'B': // ...
}// end of inner switch
case 'B': //...
}
}
Java Programming
17
Exercise: Building a Java Help
System 18
1. Create a file called Help.java.
2. The program begins by displaying the following menu:
1. Next, the program obtains the user’s selection by calling
System.in.read().
2. Once the selection has been obtained, the program
uses the switch statement to display the syntax for the
selected statement.
3. Compile and run.
Java Programming
18
9
12/10/2022
Result 19
Java Programming
19
The for loop 20
• General form:
for(initialization; condition; iteration) statement;
for(initialization; condition; iteration) {
statement sequence
}
• initialization: sets the initial value of the loop control variable
• condition: is a Boolean expression that determines whether or not
the loop will repeat.
• iteration expression defines the amount by which the loop control
variable will change each time the loop is repeated.
Java Programming
20
10
12/10/2022
Example 21
1. // Show quare roots of 1 to 99 and the rounding error.
2. public class SqrRoot {
3. public static void main(String[] args) {
4. double num, sroot, rerr;
5. for(num = 1.0; num < 100.0; num++) {
6. sroot = Math.sqrt(num);
7. System.out.println("Square root of " + num +
8. " is " + sroot);
9. rerr = num - (sroot * sroot);
10. System.out.println("Rounding error is " + rerr);
11. System.out.println();
12. }
13. }
14. }
Java Programming
21
22
1. // A negatively running for loop.
2. public class DecrFor {
3. public static void main(String[] args) {
4. int x;
5. for(x = 100; x > -100; x -=5)
6. System.out.println(x);
7. }
8. }
9.
10. for(count = 10; count < 5; count++)
11. x += count; // this statement will not execute
Java Programming
22
11
12/10/2022
Some variations on the for loop 23
1. // Use commas in a for statement
2. public class Comma {
3. public static void main(String[] args) {
4. int i, j;
5. for(i = 0, j = 10; i < j; i++, j--)
6. System.out.println("i and j: " + i + " " + j);
7. }
8. }
Java Programming
23
24
1. //Loop until an S is typed.
2. public class ForTest {
3. public static void main(String[] args)
4. throws java.io.IOException{
5. int i;
6. System.out.println("Press S to stop.");
7. for(i = 0; (char)System.in.read() != 'S'; i++)
8. System.out.println("Pass #" + i);
9. }
10. }
Java Programming
24
12
12/10/2022
Missing pieces [1] 25
1. // Parts of the for can be empty
2. public class Empty {
3. public static void main(String[] args) {
4. int i;
5. for(i = 0; i < 10;) {
6. System.out.println("Pass #" + i);
7. i++; // increment loop control var
8. }
9. }
10. }
Java Programming
25
Missing pieces [2] 26
1. // Move more out of the for loop
2. public class Empty2 {
3. public static void main(String[] args) {
4. int i = 0; // move intinitalization out of loop
5. for(; i < 10;) {
6. System.out.println("Pass #" + i);
7. i++; // increment loop control var
8. }
9. }
10. }
Java Programming
26
13
12/10/2022
The Infinite Loop 27
Consider the following code:
for(;;)
{
//...
}
This loop will run forever à infinite loop.
Java Programming
27
Loops with no body 28
1. // The body of the loop can be empty
2. public class Empty3 {
3. public static void main(String[] args) {
4. int i = 0;
5. int sum = 0;
6.
7. // sum the number through 5
8. for(i = 0; i <= 5; sum += i++);
9.
10. System.out.println("Sum is: " + sum);
11. }
12. }
Java Programming
28
14
12/10/2022
Declaring loop control variables
inside the for loop 29
1. // Declare loop control variable inside the for
2. public class ForVar {
3. public static void main(String[] args) {
4.
int sum = 0;
int fact = 1;
5.
// compute the factorial of the numbers through 5
6.
for(int i = 1; i <= 5; i++) {
7.
sum += i;// i is known throughout the loop
8.
fact *= i;
9.
}
10. //but, is is not known here
11. System.out.println("Sum is " + sum);
12. System.out.println("Factorial is " + fact);
13. }
14. }
Java Programming
29
Plan 30
1. Input characters from the keyboard
2. The if statement
3. The switch statement
4. The complete form of the for loop
5. The while loop
6. The dowhile loop
7. Use break to exit a loop
8. Use break as a form of goto
9. Apply continue
10. Nest loops
Java Programming
30
15
12/10/2022
Syntax 31
while(condition) statement;
• statement may be a single statement or a block of
statements
• condition defines the condition that controls the loop.
• The condition may be any valid Boolean expression.
• The loop repeats while the condition is true.
• When the condition becomes false, program control passes to
the line immediately following the loop.
Java Programming
31
Example 32
1. // Demonstrate the while loop
2. public class WhileDemo {
3. public static void main(String[] args) {
4. char ch;
5. // print the alphabet using a while loop
6. ch = 'a';
7. while (ch <= 'z') {
8. System.out.print(ch);
9. ch++;
10. }
11. }
12. }
Java Programming
32
16
12/10/2022
Exercise: 33
• Compute 2^i, for each i ∈ [0,10)
Java Programming
33
Plan 34
1. Input characters from the keyboard
2. The if statement
3. The switch statement
4. The complete form of the for loop
5. The while loop
6. The do while loop
7. Use break to exit a loop
8. Use break as a form of goto
9. Apply continue
10. Nest loops
Java Programming
34
17
12/10/2022
Syntax 35
do{
statements;
}while (condition);
• Difference between while loop and do ... while
loop?
Java Programming
35
Example 36
1. // Demonstrate the do-while loop
2. public class DWDemo {
3. public static void main(String[] args)
4. throws java.io.IOException{
5. char ch;
6. do {
7. System.out.print("Press a key followed by ENTER: ");
8. ch = (char) System.in.read(); // get a char
9. }while(ch !='q’);
10. }
11. }
Java Programming
36
18
12/10/2022
1. // Guess the letter game.
2.
3.
public class Guess4 {
public static void main(String[] args)
37
4. throws java.io.IOException{
5. char ch, ignore, answer = 'K';
6. do {
7. System.out.println("I'm thinking of a letter between
8. A and Z.");
9. System.out.print("Can you guess it: ");
10. ch = (char)System.in.read();
11. do { ignore = (char)System.in.read();
12. }while(ignore != '\n');
13. if(ch == answer) System.out.println("** Right **");
14. else {
15. System.out.print("...Sorry, you're ");
16. if (ch < answer) System.out.println("too low");
17. else System.out.println("too high");
18. System.out.println("Try again!\n");
19. }//end of else
20. }while(answer !=ch);
21. }
22. } Java Programming
37
Exercise: Improve the Java Help
System 38
• This exercise expands on the Java help system.
• This version adds the syntax for the for, while, and do
... while loops. It also checks the user’s menu
selection, looping until a valid response is entered.
Java Programming
38
19
12/10/2022
Plan 39
1. Input characters from the keyboard
2. The if statement
3. The switch statement
4. The complete form of the for loop
5. The while loop
6. The dowhile loop
7. Use break to exit a loop
8. Use break as a form of goto
9. Apply continue
10. Nest loops
Java Programming
39
break statement 40
• Use the break statement to force an immediate exit from
a loop, bypassing any remaining code in the body of the
loop and the loop’s conditional test.
• When a break statement is encountered inside a loop:
• the loop is terminated and
• program control resumes at the next statement following the
loop.
Java Programming
40
20
12/10/2022
Example 41
1. //Using break to exit a loop.
2. public class BreakDemo {
3. public static void main(String[] args) {
4. int num = 100;
5. //loop while i-square is less than num
6. for(int i = 0; i < num; i++) {
7. // terminate loop if i*i >= 100;
8. if (i*i >= num) break;
9. System.out.print(i + " ");
10. }
11. System.out.println("Loop complete.");
12. }
13. }
Java Programming
41
42
1. // Read input until a q is received.
2. public class Break2 {
3. public static void main(String[] args)
4. throws java.io.IOException{
5. char ch;
6. for(;;) {
7. ch = (char)System.in.read(); // get a char
8. if(ch == 'q') break;
9. }
10. System.out.println("Your pressed q!");
11. }
12. }
Java Programming
42
21
12/10/2022
1. // Using break with nested loops.
2. public class Break3 { 43
3. public static void main(String[] args) {
4. for(int i = 0; i < 3; i++) {
5. System.out.println("Outer loop count: " + i);
6. System.out.print(" Inner loop count:");
7. int t = 0;
8. while( t < 100) {
9. if( t == 10) break;
10. System.out.print(t + " ");
11. t++;
12. }
13. System.out.println();
14. }
15. System.out.println("Loops complete.");
16. }
17. }
Java Programming
43
Plan 44
1. Input characters from the keyboard
2. The if statement
3. The switch statement
4. The complete form of the for loop
5. The while loop
6. The dowhile loop
7. Use break to exit a loop
8. Use break as a form of goto
9. Apply continue
10. Nest loops
Java Programming
44
22
12/10/2022
Syntax 45
break label;
• label is the name of a label that identifies a block of
code.
Java Programming
45
1. // Using break with a label.
2.
3.
public class Break4 {
public static void main(String[] args) {
46
4. int i;
5. for(i = 1; i < 4; i++) {
6. one:{
7. two: {
8. three: {
9. System.out.println("\n i is " + i);
10. if(i == 1) break one;
11. if(i == 2) break two;
12.
if(i == 3) break three;
// this is never reached
13.
System.out.println("won't reach.");
14.
} System.out.println("After block
15.
three.");
16.
} System.out.println("After block two.");
17.
} System.out.println("After block one.");
18.
} System.out.println("After for.");
19.
}
20.
}
Java Programming
46
23
12/10/2022
47
1. // This program contains an error.
2. public class BreakErr {
3. public static void main(String[] args) {
4. one: for(int i = 0; i < 3; i++) {
5. System.out.print("Pass " + i + ": ");
6. }
7. for(int j =0; j < 100; j++) {
8. if(j == 10) break one; // WRONG
9. System.out.print(j + " ");
10. }
11. }
12. }
Java Programming
47
Plan 48
1. Input characters from the keyboard
2. The if statement
3. The switch statement
4. The complete form of the for loop
5. The while loop
6. The dowhile loop
7. Use break to exit a loop
8. Use break as a form of goto
9. Apply continue
10. Nest loops
Java Programming
48
24
12/10/2022
continue statement 49
• Forces the next iteration of the loop to take place,
skipping any code between itself and the conditional
expression that controls the loop.
Java Programming
49
Example 50
1. // Use continue.
2. public class ContDemo {
3. public static void main(String[] args) {
4. int i;
5. // print even numbers between 0 and 100
6. for(i = 0; i <= 100; i++) {
7. if ((i%2) != 0) continue; // iterate
8. System.out.println(i);
9. }
10. }
11. }
Java Programming
50
25
12/10/2022
1.
2.
// Use continue with a label.
public class ContToLabel {
51
3. public static void main(String[] args) {
4.
outerloop:
for(int i = 1; i < 10; i++) {
5.
System.out.print("\nOuter loop pass " + i +
6.
", Inner loop: ");;
7.
for(int j = 1; j < 10; j++) {
8.
// continue outer loop
9.
if(j == 5) continue outerloop;
10. System.out.print(j);
11. }
12. }
13. }
14. }
15.
Java Programming
51
Plan 52
1. Input characters from the keyboard
2. The if statement
3. The switch statement
4. The complete form of the for loop
5. The while loop
6. The dowhile loop
7. Use break to exit a loop
8. Use break as a form of goto
9. Apply continue
10. Nest loops
Java Programming
52
26
12/10/2022
53
• One loop can be nested inside of another.
• Nested loops are used to solve a wide variety of
programming problems and are an essential part of
programming.
Java Programming
53
Example 54
1. /* Use nested loops to find factors of numbers
2. * between 2 and 100.
3. */
4. public class FindFac {
5. public static void main(String[] args) {
6. for(int i = 2; i <= 100; i++) {
7. System.out.print("Factors of " + i + ": ");
8. for(int j = 2; j < i; j++)
9. if((i%j) == 0) System.out.print(j + " ");
10. System.out.println();
11. }
12. }
13. }
Java Programming
54
27
12/10/2022
55
QUESTION ?
Java Programming
55
28