Dec 18, 2007

An Iffy Brew

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.

3 comments:

Mal said...

Great job explaining if...then statements. They can be a real pain when it comes to nesting, branching, adding else's and all that other stuff in any language when you first learn them but, as usual, you rise to the occasion and provide a fabulous explanation. Keep up the good work. For some reason the link to your sample answer wouldn't work, most likely my computer, but I'm sure it's great.

Grey-M said...

Yea it doesn't work for me any more either. Have to fix that, thx for the feedback on all the posts so far.
Happy holidays,
GreyM

Mr. Kuropatwa said...

Hey GreyM,

Try posting and hosting docs at http://box.net another good online hosting solution, if you just want people to "see" (and hear as mp3s automatically generated by the site) is http://scribd.com.

Cheers!