Java Reference
In-Depth Information
FIGURE 3-2
This provides an explicit choice between two courses of action — one for when the if expression is true
and another for when it is false .
You can apply this in a console program and try out the random() method from the Math class at the
same time.
TRY IT OUT: if-else
When you have entered the program text, save it in a file called NumberCheck.java . Compile it and then
run it a few times to see what results you get.
public class NumberCheck {
public static void main(String[] args) {
int number = 0;
number = 1+(int)(100*Math.random());// Get a random integer
between 1 & 100
if(number%2 == 0) { // Test if it is even
System.out.println("You have got an even number, " + number);//
It's even
} else {
System.out.println("You have got an odd number, " + number); //
It's odd
}
}
}
 
Search WWH ::




Custom Search