Java TOPIC 16 – IF STATEMENTS - PART
3 LESSON NOTE ADDING RANDOMNESS TO
PROGRAMS
EXAMPLE 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. |
|
|