mju516
mju516

Reputation: 125

Reading ints into a multidimensional array

My problem occurs during the for loops to read in the values from the file into my scores array. The program reads in and prints the first 6 values or 2 lines of ints, but then I get ArrayIndexOutOfBoundsException: 2

I have no idea why this is stopping there. If I have j<1000, it will read 17 values. Anyway, the file I'm reading in is below (wasn't sure the formatting for a text file).

Any help would be appreciated

Andy Matt Tom

3    2     3

4   4   5

3   3   2

2   2   2

2   4   2

2   3   2

4   4   5

2   3   3

4   3   5

3   3   6

2   2   5

3   3   3

3   3   2

3   2   4

3   2   6

3   4   3

2   3   2

2   2   2

50  52  62


public static void main( String args[] )
{
    try
    {

    if (args.length<1)
    {
        System.out.printf("\n...You must enter the name of a file\n");
        System.exit(0);
    }

    Scanner infile  = new Scanner ( new File(args[0]) );


    int par= 3;
    int play= 18;
    String[] players= new String[play];
    int k=0;
    int scores[][]= new int[play-1][par-1];

    while(infile.hasNext())
    {
    players[k]=infile.next();

    k++;

    if (k==play)
    break;
    }


    for(int j=0; j<par; j++)
    {
        for (int i=0; i<play; i++)
        {
        scores[j][i]=infile.nextInt();
        System.out.println(scores[j][i]);
        }

    }

    }
    catch (FileNotFoundException e)
    {
    System.out.println("Bug");
    System.exit(0);
    }

}

Upvotes: 0

Views: 108

Answers (3)

Manish
Manish

Reputation: 3522

Actually, there are three issues.

  1. There are only 3 players, not 18
  2. You need a 18x3 array, not a 17x2 array
  3. [i][j] instead of [j][i]

Diff of your code against my modified version (which works like a charm):

22c22
<     String[] players= new String[play];
---
>     String[] players= new String[par];
24c24
<     int scores[][]= new int[play-1][par-1];
---
>     int scores[][]= new int[play][par];
32c32
<     if (k==play)
---
>     if (k==par)
41,42c41,42
<         scores[j][i]=infile.nextInt();
<         System.out.println(scores[j][i]);
---
>         scores[i][j]=infile.nextInt();
>         System.out.println(scores[i][j]);

Upvotes: 0

hmjd
hmjd

Reputation: 121961

There are two issues:

int scores[][] = new int[play-1][par-1]; // Why -1 ?

and:

for(int j=0; j<par; j++)              // should be 'j < play' as 'j'
                                      // is index to dimension
                                      // with size 'play'
{
    for (int i=0; i<play; i++)        // should be 'i < par' as 'i' is
                                      // index to dimension with
                                      // size 'par'
    {
        scores[j][i]=infile.nextInt();
        System.out.println(scores[j][i]);
    }
}

Upvotes: 1

Kevin
Kevin

Reputation: 56049

int scores[][] = new int [play-1][par-1];

Why -1? That's where your AIOOB is coming from.

Upvotes: 1

Related Questions