Friday, 19 December 2014

Combining Java Conditional Statements With Else

The program below uses IF, ELSE IF and ELSE to test the distribution of random numbers produced by Java: 

Java > cat prog49.java
public class prog49
{
public static void main (String args[])
 {
 int one = 0;
 int two = 0;
 int three = 0;
 int x;
 for(x=1;x<=30000;x++)
  {
  int random1 = (int)(Math.random()*3)+1;
  if (random1 == 1)
   one++;
  else
  if (random1 == 2)
    two++;
   else
    if (random1 == 3)
     three++;
    else
     System.out.println("Program error");
  }
 System.out.println("Number of 1's = " + one);
 System.out.println("Number of 2's = " + two);
 System.out.println("Number of 3's = " + three);
 }
}
Java > javac prog49.java
Java > java prog49
Number of 1's = 9986
Number of 2's = 10053
Number of 3's = 9961
Java >