Completion requirements
This chapter discusses the 'for' loop in greater detail, as well as the scope of variables in the 'for' loop.
5. Keep things local
Answer:
No. The second for
loop is trying to use a variable j
that is not defined at that point.
(The first for
statement declares a j
than can only be seen within that loop.)
<table width=100% style="border: 5px double red;">
<tbody>
<tr>
</tr>
<tr>
<td style="border: 5px double red;">
<pre><pre>TEXT</pre></pre>
</td>
</tr>
</tbody>
</table>
Keep things local
Here is another version of the program, which is syntactically correct, but is not nicely done.
public class FoolishTypist { public static void main ( String[] args ) { int sumEven = 0; int sumOdd = 0; int j; // Same "j" used for both loops. for ( j = 0; j < 8; j=j+2 ) sumEven = sumEven + j; System.out.println( "The sum of evens is: " + sumEven ); for ( j = 1; j < 8; j=j+2 ) sumOdd = sumOdd + j; System.out.println( "The sum of odds is: " + sumOdd ); } } |
It is best to keep sections of code self-contained. With this (unwise) version, both loops depend on something distant from themselves. Although this program is clear enough, a longer program might be harder to understand. Here, for instance, is a typical hard to understand program:
public class FoolishTypist { public static void main ( String[] args ) { int sumEven = 0; int sumOdd = 0; int j = 0; int i = 1; for ( j = 0; j < 8; j=j+2 ) sumEven = sumEven + j; System.out.println( "The sum of evens is: " + sumEven ); for ( i = 1; i < 8; i=i+2 ) sumOdd = sumOdd + j; System.out.println( "The sum of odds is: " + sumOdd ); } } |
Question 5:
- Will this new program compile?
- Will it run?
- Is it correct?