While we can do more complex things now, we still have to program one command for every single thing we want to do. In order for the computer to be helpful to us, we need to be able to give it a task and have it do it over and over again, or to be able to give it a task, and perform one or more other tasks based on the outcome of the first.
Consider a program written to mimic the activity of a town crier.
The town crier goes out every hour on the hour and announces the time.
public class TownCrier {
public static void main (String [] args) {
for (int i=0; i<24; i++) {
System.out.println(""+i+":00 hours and all is well!");
}
}
}
This code uses a familiar type of loop called a 'for' loop. You start
with your index variable (in this case i) set to some initial value
(int i=0). You perform some check to see if a condition is true, in this
case we are checking to see that i is less tha 24 (i<24). Then you
set up an increment to change your index each time through the loop,
here we increase i by 1 (i++, we could also have used i=i+1. or i+=1).
For each value of i as you go through the loop, you perform the associated
commands.
Conditional Statements
Notice that we control the loop with a condition. Essentially,
each time through the loop it checks to see if i is less that 24.
We can also have statements that check for conditions. These are
called if statements.
Suppose we lived in the same town as the crier, and wanted our sleep
in the evening. We might ask the crier to only announce the time IF
the time is when people are awake.
public class TownCrier {
public static void main (String [] args) {
for (int i=0; i<24; i++) {
if (i>=6&&i<=22) {
System.out.println(""+i+":00 hours and all is well!");
} else {
System.out.println("Zzzzzz.");
}
}
}
}
The While Loop
Another type of loop is the while loop. Sometimes instead of doing
a procedure a set number of times, we just want to keep doing it
until it is done, or until some condition is true.
Consider a simple program to represent a gambler who squanders all
of his money on a series of 50/50 bets. The gambler starts with a balance
of 5 dollars, and always bets one dollar. You might want to program this
by having the gambler keep betting WHILE he has money to bet.
public class TheGambler {
public static void main(String [] args) {
double balance=5.0;
while (balance>0.0) {
if (Math.random()>0.5) {
balance+=1.0;
System.out.println("Winner! balance = "+balance);
} else {
balance-=1.0;
System.out.println("Loser! balance = "+balance);
}
}
}
}
Notice that to do this we use one of the routines in the java.lang.Math
class. Math.random() returns a random double between 0 and 1.
Exercise
Modify the program so that the gambler wins 1/4 of the time, but wins
twice the amount bet. Does this improve the gambler's odds?