go to previous page   go to home page   go to next page hear noise

Answer:

for ( int index= egArray.length-1 ; index >= 0 ; index-- )

I win! You forgot the -1. Off-by-one errors of this kind are very common. It was an easy bet.


Reading in Each Element

Here is a program that prompts the user for each element of an array and reads it in. The array is hard coded to be five elements long. After it is filled with data, the array is written to the monitor.

Usually a program would do something with the data (besides just print it out) after it was read in. This would usually involve more loops.


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 (  ;  ;  )
    {
      System.out.println( "enter an integer: " );
      data = scan.nextInt();
      array[ index ] = data ;
    }
      
    // write out the data
    for (  ;  ;   )
    {
      System.out.println( "array[ " + index + " ] = " + array[ index ] );
    }

  }
}      

QUESTION 4:

Fill in the blanks so that the program works as described. You may wish to copy and paste some of the following phrases. (Hint: you will need to use most phrases twice.)

int index
index <
= 0
index++
array.length