go to previous page   go to home page   go to next page

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.)

class SameName
{
  public static void main ( String[] args )
  {
    int sumEven = 0;
    int sumOdd  = 0;

    for ( int 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 )    //  "j" can not be seen at this point.
        sumOdd  = sumOdd + j;                     

    System.out.println( "The sum of odds is: " + sumOdd );
  } 
}

Keep things local

Here is another version of the program, which is syntactically correct, but is not nicely done.

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:

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:

  1. Will this new program compile?
  2. Will it run?
  3. Is it correct?