Java

TOPIC 16 – IF STATEMENTS - PART 3

 

 

LESSON NOTE

 

 

ADDING RANDOMNESS TO PROGRAMS


We have already seen how to generate a random number.  The Math function random() generates a random number between 0 and 0.999999999999. 

We can use this along with IF statements to add some randomness to our programs.

 

EXAMPLE

Write a program that will ask for your name and respond with a greeting.  Half of the time, it will say "Hello name".  Forty percent of the time it will say "Hey there name".  And ten percent of the time it will say "Howdy name!".

         Scanner scr = new Scanner(System.in);

         System.out.println("Enter your name");

         String name = scr.nextLine();

        

         double random = Math.random();

         if(random < 0.5)

         {

             System.out.println("Hello " + name);

         }

         else if (random < 0.9)

         {

             System.out.println("Hey there " + name);

         }

         else

         {

             System.out.println("Howdy " + name);

         }

 

EXPLANATION

 

After getting the user's name, we generate a random number and store it in the variable called random. 

 

We then check if random is less than 0.5.  There is a 50% chance that it is.  If it is, we output the first greeting and jump to the end of the program.

 

If random is not less than 0.5, we go to the next condition which is checking if random is less than 0.9.  Because random is not less than 0.5, we are really checking if random is between 0.5 and 0.9.  There is a 40% chance that it is.  If it is, we output the second greeting and jump to the end of the program.

 

If random is not less that 0.9, then we go to the ELSE block.  There is a 10% chance that we get here.  And we output the third greeting.