Random Number Function
Write your own method and call it.
1public static void randomNumber() {
2 double num = Math.random();
3 num = num * 10;
4 System.out.println(num);
5}
6
7public static void main(String[] args) {
8 randomNumber();
9}
$ javac Main.java
$ java Main
(prints a random number, different every run)
Every line, explained
public static void randomNumber() {- This defines a method: a named block of code you can run whenever you want by calling its name. void means it does not hand back a result, and static lets main call it directly. Methods are written next to main, not inside it. We define it first, then use it in main below, though Java itself does not mind the order.
double num = Math.random();- double declares a variable for decimal numbers (like 0.37 or 9.99). Math.random() returns a random decimal that is at least 0.0 and less than 1.0, different every time you run the program!
num = num * 10;- This multiplies num by 10 and stores the result back into num. Now it is a random decimal between 0.0 and 10.0 (never quite reaching 10). No type word here: num already exists, we are just giving it a new value.
System.out.println(num);- 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". Because num is a double, you will see a long decimal number.
}- This } closes the randomNumber 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.
randomNumber();- This line calls (runs) the randomNumber method we defined above. When Java reaches this line it jumps into randomNumber, runs its code, then comes back here. Remember: the program still starts at main; defining a method does nothing until somebody calls it.
}- This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.