Page 179 - Introduction to Programming with Java: A Problem Solving Approach
P. 179
2. [after §4.8] Given this code fragment:
1
double x = 2.1;
while (x * x <= 50)
2
3
4{
5
switch ((int) x)
6{
7
case 6:
x--;
System.out.println("case 6, x= " + x);
case 5:
System.out.println("case 5, x= " + x);
case 4:
System.out.println("case 4, x= " + x);
break;
default:
System.out.println("something else, x= " + x);
// end switch
+=2;
8
9
10
11
12
13
14
15
16
17
}
x
18
19
} // end while
Trace the code using either the short form or the long form. To help you get started, here’s the trace setup. For the short form, you won’t need the line# column.
Apago PDF Enhancer
x output
3. [after §4.9] The following main method is supposed to print the sum of the numbers 1 through 5 and the product of the numbers 1 through 5. Find all the bugs in the program and fix them. Do not add or delete statements. Just fix existing statements. We encourage you to check your work by running test code on a computer.
public static void main(String[] args)
Exercises 145
{
}
// end main
int count = 0;
int sum = 0;
int product = 0;
do
{
}
count++;
sum += count;
product *= count;
if (count == 5)
System.out.println("Sum = " + sum);
System.out.println("Product = " + product);
while (count < 5)
line#
Intended output:
Sum = 15
Product = 120