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

Answer:

The two lines:

      data  = scan.nextInt();
      array[ index ] = data ;

can be replaced by the single line:

       array[ index ] = scan.nextInt();

And then the declaration int data; should be removed.

Run-time Array Length

An array object is constructed as the program runs (as are all objects). When an array is constructed, its size can be in a variable. Here is the previous example, with some modifications:

import java.util.Scanner ;

class InputArray
{

  public static void main ( String[] args )
  {

    int[] array;
    int   data;
    Scanner scan = new Scanner( System.in );

    // determine the size and construct the array
    System.out.print( "What length is the array? " );
    int size  = scan.nextInt();

    array     = new int[  ]; 

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

  }
}      

QUESTION 6:

Fill in the blank.