Saturday 20 December 2014

Java switch Statement

This is a variation on the previous post but using the switch statement instead of if / else if / else. You can use the switch statement to compare a variable with a series of fixed values preceded by the word case. Specific actions can be carried out after each case statement if the variable matches the value specified. The default statement at the end says what to do if the variable does not match any of the values provided: 

andrew@UBUNTU:~/Java$ cat prog50.java
import java.util.Random;
public class prog50
{
public static void main (String args[])
 {
 int zero = 0;
 int one = 0;
 int two = 0;
 Random random_number = new Random();
 int upper_limit = 3;
 int x;
 for(x=1;x<=30000;x++)
  {
  int y = random_number.nextInt(upper_limit);
  switch (y)
   {
   case 0:
    zero++;
    break;
   case 1:
    one++;
    break;
   case 2:
    two++;
    break;
   default:
    System.out.println("Program error");
    break;
   }
  }
 System.out.println("Number of 0's = " + zero);
 System.out.println("Number of 1's = " + one);
 System.out.println("Number of 2's = " + two);
 }
}
andrew@UBUNTU:~/Java$ javac prog50.java
andrew@UBUNTU:~/Java$ java prog50
Number of 0's = 9989
Number of 1's = 10109
Number of 2's = 9902
andrew@UBUNTU:~/Java$