Java Reference
In-Depth Information
Similarly, the loop in (c) is also wrong. (c) is equivalent to (d). Both are incorrect.
Empty body
Error
int i = 0 ;
while (i < 10 );
{
System.out.println( "i is " + i);
i++;
}
int i = 0 ;
while (i < 10 ) { };
{
System.out.println( "i is " + i);
i++;
}
(c)
(d)
These errors often occur when you use the next-line block style. Using the end-of-line
block style can avoid errors of this type.
In the case of the do-while loop, the semicolon is needed to end the loop.
int i = 0 ;
do {
System.out.println( "i is " + i);
i++;
} while (i < 10 );
Correct
5.15
Can you convert a for loop to a while loop? List the advantages of using for loops.
Check
5.16
Can you always convert a while loop into a for loop? Convert the following while
loop into a for loop.
Point
int i = 1 ;
int sum = 0 ;
while (sum < 10000 ) {
sum = sum + i;
i++;
}
5.17
Identify and fix the errors in the following code:
1 public class Test {
2 public void main(String[] args) {
3 for ( int i = 0 ; i < 10 ; i++);
4 sum += i;
5
6 if (i < j);
7 System.out.println(i)
8 else
9 System.out.println(j);
10
11 while (j < 10 );
12 {
13 j++;
14 }
15
16 do {
17 j++;
18 } while (j < 10 )
19 }
20 }
 
 
Search WWH ::




Custom Search