Java Reference
In-Depth Information
limit == 4
n == 4
limit == 5
38. 8
6
The end.
39. 8
6
2
0
The end.
40. If you look at the trace, you will see that after one iteration, the value of sum
is 20. But the value should be 10 + 9, or 19. This should lead you to think that
the variable n is not decremented at the correct time. Indeed, the bug is that the
two statements
sum = sum + n;
n-- ;
should be reversed to
n-- ;
sum = sum + n;
41. int n, sum = 0;
for (n = 1; n < 10; n++)
{
System.out.println("n == " + n + " sum == " + sum);
// Above line is a trace .
sum = sum + n;
}
System.out.println("After loop");//trace
System.out.println("n == " + n + " sum == " + sum);//trace
System.out.println("1 + 2 + ...+ 9 + 10 == " + sum);
If you study the output of this trace, you will see that 10 is never added in. This
is a bug in the loop.
42. This is the code you traced in the previous exercise. If you study the output of this
trace, you will see that 10 is never added in. This is an off-by-one error.
43. assert (time <= limit);
44. 10, 11, 12, 13 or 14
45. A double that is greater than or equal to 1 but less than 4.
46. double d = Math.random() * 10 + 10;
Search WWH ::




Custom Search