Java Reference
In-Depth Information
You can then refine this pseudocode by introducing a variable for the number that
is read from the user:
sum = 0.
prompt and read a value into n.
while (n is not the sentinel) {
add n to the sum.
prompt and read a value into n.
}
This pseudocode translates fairly easily into Java code:
Scanner console = new Scanner(System.in);
int sum = 0;
System.out.print("next integer (-1 to quit)? ");
int number = console.nextInt();
while (number != -1) {
sum += number;
System.out.print("next integer (-1 to quit)? ");
number = console.nextInt();
}
System.out.println("sum = " + sum);
When the preceding code is executed, the interaction might look like this:
next integer (-1 to quit)? 34
next integer (-1 to quit)? 19
next integer (-1 to quit)? 8
next integer (-1 to quit)? 0
next integer (-1 to quit)? 17
next integer (-1 to quit)? 204
next integer (-1 to quit)? -1
sum = 282
Fencepost with if
Many of the fencepost loops that you write will require conditional execution. In fact,
the fencepost problem itself can be solved with an if statement. Remember that the
classic solution to the fencepost is to handle the first post before the loop begins:
plant a post.
for (the length of the fence) {
attach some wire.
plant a post.
}
 
Search WWH ::




Custom Search