Hello everybody,
Today we make some decisions, well the computer will. We are going to do "if" tests(! These are core elements that allow computers to make decisions that are based on a condition.)
If's take the general form of...
If (argument) {
code to run if true
}
The argument can be many things, generally they compare two things but it can be a boolean (true or false variable).
You can add an else as well...
If (argument) {
code to run if true
} else {
code to run if false
}
So to try this out we'll make a quick program to check if a number we generate is greater than or less than fifty.
public class OddOrEven{
public static void main(String[] args) {
double z = Math.random() * 100;
if (z <>
System.out.print("Less than 50");
} else {
System.out.print("Greater than 50");
}
}
}
We have our class in blue because all programs need a class.
Then we have our main method, it is the method that runs first.
In purple we have our statements
-double z = Math.random() * 100;
-"double z" declares a double(a decimal value that can hold more information then a single) named z
-"= Math.random() * 100 " generates a pseudorandom number from 0 to 1 (computers can have true randomness), by multiplying by 100 we get a number between 0 and 100.
In brown we have our if else block.
If statements can also be nested which means an if block within an if block.
if (argument) {
code to run if just the first one is true
if (argument) {
code to run if both are true
}
}
Why don't you try to make a program that checks if the integer z is > 50 and if it is check if it is less than 75 and if z <> 25.
Good luck!
My sample answer is here.
Dec 18, 2007
Subscribe to:
Posts (Atom)