Find Five
Keep calling a method until it returns 5.
1public static int findFive() {
2 double num = Math.random();
3 num = num * 10;
4 int maybeFive = (int) Math.floor(num);
5 return maybeFive;
6}
7
8public static void main(String[] args) {
9 int number = findFive();
10 while (number != 5) {
11 System.out.println(number);
12 number = findFive();
13 }
14 System.out.println(number);
15}
$ javac Main.java
$ java Main
(prints a random number, different every run)
Every line, explained
public static int findFive() {- This method promises to hand back an int; that is why it says int instead of void. Whoever calls findFive() receives a whole number in return. We define it first, then use it in main below.
double num = Math.random();- Math.random() gives a random decimal that is at least 0.0 and less than 1.0.
num = num * 10;- Scales the random decimal up to somewhere between 0.0 and 10.0.
int maybeFive = (int) Math.floor(num);- Math.floor rounds a decimal DOWN to a whole number: 7.83 becomes 7.0. Its answer is still a double, so (int) converts ("casts") it into an int so it fits in an int variable. Result: a random whole number from 0 to 9.
return maybeFive;- return hands the value back to whoever called the method, and the method ends. Because the method promised an int, it must return an int.
}- This } closes the findFive method.
public static void main(String[] args) {- Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
int number = findFive();- This calls the findFive method we wrote above. It hands back a random whole number from 0 to 9, which is stored in the variable number.
while (number != 5) {- A while loop repeats its block for as long as the condition in the parentheses is true. The condition is checked again before every trip around the loop. != means "not equal". The loop keeps running as long as number is NOT 5.
System.out.println(number);- System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". Prints each wrong guess.
number = findFive();- Asks findFive for a fresh random number and stores it, replacing the old one. Then the loop checks the condition again.
}- This } closes the while loop.
System.out.println(number);- System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". The loop only ends when number is finally 5, so this prints the 5 we were hunting for.
}- This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.