Jake
Jake

Reputation: 29

2D array with user input

I want to create a 5 row 2 column int array and have the user input each value in the array. I want to use StdIn for the input. Why won't this work? Please help! Thanks.

This is my effort:

int [][] a = new int [5][2];

int i;
int j;

for( i = 0; i < 4; i++ );
{
  for( j = 0; j < 2; j++ );
  {
    System.out.println( "Month number (e.g. August = 8)" );
    int month = StdIn.readInt();
    a[i][0] = month;

    System.out.println( "Year number (e.g. 2007)" );                
    int year = StdIn.readInt();
    a[i][1] = year;

  }
}

Upvotes: 0

Views: 300

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

You're already asking both values from the user, no need for the nested loop:

int [][] a = new int [5][2];
for(int i = 0; i < 5; i++ )
{
    System.out.println( "Month number (e.g. August = 8)" );
    int month = StdIn.readInt();
    a[i][0] = month;

    System.out.println( "Year number (e.g. 2007)" );                
    int year = StdIn.readInt();
    a[i][1] = year;

}

I've also removed the semicolon ; you had after the first for loop making it useless, and fixed the iteration to get to 4 ( you're looping [0..4) and you probably want [0..5) ).

j was removed since the nested loop was not needed and I've make i local to the for loop.

Upvotes: 2

Related Questions