Home » Java » Control Flows

Category Archives: Control Flows

Control Flows

The If Statement

1
if (condition) statement;

or

1
2
3
if (condition) {
    zero to many statements;
}

Causes “one thing” to occur when a specified condition is met.

The one thing may be a single statement or a block of statements in curly braces. The remainder of the code (following the if and the statement or block it owns) is then executed regardless of the result of the condition.

The conditional expression is placed within parentheses.

The following flowchart shows the path of execution:

If Statement Flowchart

if Statement Examples

Absolute Value

If we needed the absolute value of a number (a number that would always be positive):

Code Sample:

Java-Control/Demos/If1.java
1
2
3
4
5
6
7
8
9
10
11
12
public class If1 {
  public static void main(String[] args) {
    int a = 5;
    System.out.println("original number is: " + a);
    if ( a < 0 ) { a = -a; }
    System.out.println("absolute value is: " + a);
    a = -10;
    System.out.println("original number is: " + a);
    if ( a < 0 ) { a = -a; }
    System.out.println("absolute value is: " + a);
  }
}

Random Selection

Task: write a brief program which generates a random number between 0 and 1. Print out that the value is in the low, middle, or high third of that range (Math.random() will produce a double value from 0.0 up to but not including 1.0).

  • Although it is a bit inefficient, just do three separate tests: (note that Math.random() will produce a number greater than or equal to 0.0 and less than 1.0).

Code Sample:

Java-Control/Demos/If2.java
1
2
3
4
5
6
7
8
9
10
11
12
public class If2 {
  public static void main(String[] args) {
    double d = Math.random();
    System.out.print("The number " + d);
    if (d < 1.0/3.0)
      System.out.println(" is low");
    if (d >= 1.0/3.0 && d < 2.0/3.0)
      System.out.println(" is middle");
    if (d >= 2.0/3.0)
      System.out.println(" is high");
  }
}

The if ... else Statement

1
2
3
if (condition) statement;
else if { block } statement;
else { block }

The if … else Statement does “one thing” if a condition is true, and a different thing if it is false.

It is never the case that both things are done. The “one thing” may be a single statement or a block of statements in curly braces.

A statement executed in a branch may be any statement, including another if or if ... else statement.

If ... Else Statement Flowchart

This program tells you that you are a winner on average once out of every four tries.

Code Sample:

Java-Control/Demos/IfElse1.java
1
2
3
4
5
6
7
public class IfElse1 {
  public static void main(String[] args) {
    double d = Math.random();
    if (d < .25) System.out.println("You are a winner!");
    else System.out.println("Sorry, try again!");
  }
}

Nested if ... else Statements – Comparing a Number of Mutually Exclusive Options

You can nestif ... else statements, so that an if or else clause contains another test. Both the if and the elseclause can contain any type of statement, including another if or if ... else.

You can test individual values or ranges of values. Once an if condition is true, the rest of the branches will be skipped. You could also use a sequence of if statements without the else clauses (but this doesn’t by itself force the branches to be mutually exclusive).

Here is the low/middle/high example rewritten using if ... else

Code Sample:

Java-Control/Demos/IfElse2.java
1
2
3
4
5
6
7
8
9
10
11
12
public class IfElse2 {
  public static void main(String[] args) {
    double d = Math.random();
    System.out.print("The number " + d);
    if (d < 1.0/3.0)
      System.out.println(" is low");
    else if (d < 2.0/3.0)
      System.out.println(" is middle");
    else
      System.out.println(" is high");
  }
}

Similarly, we do not test the high third at all. The original version worked because there was no chance that more than one message would print; that approach is slightly less efficient because all three tests will always be made. In the if ... else version, comparing stops once a match has been made.

The switch Statement

A switch expression (usually a variable) is compared against a number of possible values. It is used when the options are each a single, constant value that is exactly comparable (called a case).

The switch expression must be a bytecharshort, or int. Cases may only be bytecharshort, or int values; in addition, their magnitude must be within the range of the switch expression data type and cannot be used with floating-point datatypes or long and cannot compare an option that is a range of values, unless it can be stated as a list of possible values, each treated as a separate case.

Cases are listed under the switch control statement, within curly braces, using the case keyword. Once a match is found, all executable statements below that point are executed, including those belonging to later cases; this allows stacking of multiple cases that use the same code.

The break; statement is used to jump out of the switch block, thus skipping executable steps that are not desired. The default case keyword catches all cases not matched above – note that the default case does not need to be the last thing in the switch. Note that technically speaking, the cases are labeled lines; the switch jumps to the first label whose value matches the switch expression.

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
switch ( <span class="Subst">expression</span> ) {
    case constant1:
        statements;
        break;
    case constant2:
        statements;
        break;
    . . .
    case constant3:
    case constant4:
        MeansTheSameAs3:
        statements;
        break;
    . . .
    [default:
        statements;]
}

switch Statement Examples

Code Sample:

Java-Control/Demos/Switch1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import util.KeyboardReader;
public class Switch1 {
  public static void main(String[] args) {
    char c = 'X';
    c = KeyboardReader.getPromptedChar("Enter a letter a - d: ");
    switch (c) {
      case 'a':
      case 'A': System.out.println("A is for Aardvark");
                break;
      case 'b':
      case 'B': System.out.println("B is for Baboon");
                break;
      case 'c':
      case 'C': System.out.println("C is for Cat");
                break;
      case 'd':
      case 'D': System.out.println("D is for Dog");
                break;
      default:  System.out.println("Not a valid choice");
    }
  }
}

Three points to note:

  • Stacking of cases for uppercase and lowercase letters allows both possibilities.
  • break; statements used to separate code for different cases.
  • default: clause used to catch all other cases not explicitly handled.

Here is a revised version that moves the default to the top, so that a bad entry is flagged with an error message, but then treated as an ‘A’ – note that there is no break below the default case.

Code Sample:

Java-Control/Demos/Switch2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import util.KeyboardReader;
public class Switch2 {
  public static void main(String[] args) {
    char c = 'X';
    c = KeyboardReader.getPromptedChar("Enter a letter a - d: ");
    switch (c) {
      default:  System.out.println("Not a valid choice - assuming 'A'");
      case 'a':
      case 'A': System.out.println("A is for Aardvark");
                break;
      case 'b':
      case 'B': System.out.println("B is for Baboon");
                break;
      case 'c':
      case 'C': System.out.println("C is for Cat");
                break;
      case 'd':
      case 'D': System.out.println("D is for Dog");
                break;
    }
  }
}

Another example is taking advantage of the “fall-though” behavior without a break statement.

Code Sample:

Java-Control/Demos/Christmas.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import util.KeyboardReader;
public class Christmas {
  public static void main(String[] args) {
    int day = KeyboardReader.getPromptedInt("What day of Christmas? ");
    System.out.println(
        "On the " + day + " day of Christmas, my true love gave to me:");
    switch (day) {
      case 12: System.out.println("Twelve drummers drumming,");
      case 11: System.out.println("Eleven pipers piping,");
      case 10: System.out.println("Ten lords a-leaping,");
      case 9: System.out.println("Nine ladies dancing,");
      case 8: System.out.println("Eight maids a-milking,");
      case 7: System.out.println("Seven swans a-swimming,");
      case 6: System.out.println("Six geese a-laying,");
      case 5: System.out.println("Five golden rings,");
      case 4: System.out.println("Four calling birds,");
      case 3: System.out.println("Three French hens,");
      case 2: System.out.println("Two turtle doves, and a ");
      case 1: System.out.println("Partridge in a pear tree!");
    }
  }
}
Advertisements