简体   繁体   中英

In Java, why isn't nextInt() retrieving every number from this text file?

  public GameofLife(int gen)
  {
   generations = gen; 
   life = new boolean[20][20];
   try {
      Scanner pablo = new Scanner(new File("life100.txt"));
      pablo.nextInt(); //eliminate 100 (number of files in the list)
      while (pablo.hasNextInt())
          {
            life[pablo.nextInt()][pablo.nextInt()] = true;
          }
        } catch(Exception e){}
     out.print(Arrays.deepToString(life));
    }

I'm trying to read in 100 pairs int coordinates for an array from a text file, but for some reason this setup doesn't get every number; after it reads in row 3 it stops. The text file is in the setup

100
1    3
1    7
1    8
1   11
1   12
1   17
2    1
2    5
2    8
3    7
3   13
3   16
3   20
4    1
4    5
4   15
4   17

and goes all the way up to 19 18. Yet when I print it, with the out.print(Arrays.deepToString(life)); , every position after row three is false, whereas I'm setting this up so that every pair of coordinates on the text file starts as true in the matrix.

Is this a problem with my nextInt() scanner function? Or something else? And what is the best way to fix it? Please I need help. Any advice, comments, or ideas are welcome. Thank you

If that's the actual file content it looks like you're exceeding the bounds of your array when it reads in 3 20 There is no [3][20] allocated in life , it would only go out to [3][19] .

This is being obscured by your try/catch block which catches and drops the ArrayIndexOutOfBoundsException . As the comments suggest, printing a stack trace is a better default catch behavior than doing nothing, which would quickly reveal this error.

Try putting e.printStackTrace(); in the catch block to see what I'm talking about.

Since Java arrays are indexed starting from 0, if your file contains row+column positions going from 1 to 20, you need to subtract 1 from the value in the file before adding it to the array, eg

life[pablo.nextInt() - 1][pablo.nextInt() - 1] = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM