Line At A Time
Lesson 25: Find Fifty
Find Fifty Same hunt, bigger haystack: find 50 out of 100.
1public static int findFifty() {
2 double num = Math.random();
3 num = num * 100;
4 int maybeFifty = (int) Math.floor(num);
5 return maybeFifty;
6}
7
8public static void main(String[] args) {
9 int number = findFifty();
10 while (number != 50) {
11 System.out.println(number);
12 number = findFifty();
13 }
14 System.out.println(number);
15}
Terminal
$ javac Main.java
$ java Main
(prints a random number, different every run)
Every line, explained
public static int findFifty() {
A method that promises to hand back an int: a random whole number from 0 to 99.
double num = Math.random();
Math.random() gives a random decimal that is at least 0.0 and less than 1.0.
num = num * 100;
Scales the random decimal up to somewhere between 0.0 and 100.0.
int maybeFifty = (int) Math.floor(num);
Math.floor rounds the decimal DOWN, and (int) casts the result into a whole number from 0 to 99.
return maybeFifty;
Hands the value back to whoever called findFifty().
}
This } closes the findFifty 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 = findFifty();
Calls the findFifty method we wrote above and stores the random whole number (0 to 99) it hands back.
while (number != 50) {
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. The loop keeps running as long as number is NOT 50. With 100 possibilities this usually takes a lot more tries than finding 5 out of 10!
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. Expect a lot of them.
number = findFifty();
Asks findFifty for a fresh random number, then the loop checks 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". Prints the 50 that finally ended the loop.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.