Complete Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

The complete program is given below.

Complete Program

Notice that the two for loops are the same. This is very common. It would be nice to copy this program to a file and to run it. When you do this, change the length of the array (the 5) to some other value (say, 9) and note the effect.

import java.util.Scanner ;

class InputArray
{

  public static void main ( String[] args )
  {

    int[] array = new int[5];
    int   data;

    Scanner scan = new Scanner( System.in );

    // input the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "enter an integer: " );
      data = scan.nextInt();
      array[ index ] = data ;
    }
      
    // write out the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "array[ " + index + " ] = " + array[ index ] );
    }

  }
}      

Review: Recall that the scope of the identifier index declared in the for statement is limited to just the body of its loop. So in the above, there are two variables, each named index, and each limited in scope to the body of its own for.

QUESTION 5:

The variable data is not really needed in this program. Mentally change the program so that this variable is not used.