Reading in Each Element

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:

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.

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 ] );
    }

  }
}      

Usually a program would do something with the data after it was read in. This would usually involve more loops.

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