Java Reference
In-Depth Information
35. Write the while loop of Exercise 34 as a do ... while loop.
36. The do ... while loop in the following program is intended to read some
numbers until it reaches a sentinel (in this case, -1 ). It is supposed to add all
of the numbers except for the sentinel. If the data looks like:
12 5 30 48 -1
the program fails to work as intended. Make any necessary corrections.
import java.util.*;
public class Strange
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int total = 0;
int number;
do
{
number = console.nextInt();
total = total + number;
}
while (number != -1);
System.out.println("The sum of the numbers entered is "
+ total);
}
}
37. Using the same data as in Exercise 36, the following loop also fails. Correct it.
number = console.nextInt();
while (number != -1)
total = total + number;
number = console.nextInt();
System.out.println();
System.out.println(total);
38. Using the same data as in Exercise 36, the following loop also fails. Correct it.
number = console.nextInt();
while (number != -1)
{
number = console.nextInt();
total = total + number;
}
System.out.println();
System.out.println(total);
Search WWH ::




Custom Search