-3

我在弄清楚为什么这不起作用时遇到了一些麻烦。有任何想法吗?

      try {
           Scanner scanner = new Scanner(new File("/Users/xxxxxxx/Desktop/baseball_in.txt"));
           String[][] myStringArray = new String [40][40];
           for (int i=0; scanner.hasNext(); i++) {
               for(int x=0; x<7; x++){
                   myStringArray[i][x] = scanner.next();
               }
           }
           System.out.println(Arrays.deepToString(myStringArray));
           scanner.close();
          } catch (FileNotFoundException e) {
          }
         }
4

1 回答 1

3

scanner您仅在每 7 次调用时检查是否有下一个元素scanner.next()。因此,当您连续调用7 次时,很可能scanner没有下一个元素可以获取。scanner.next()

做:

try {
       Scanner scanner = new Scanner(new File("/Users/xxxxxxx/Desktop/baseball_in.txt"));
       String[][] myStringArray = new String [40][40];
       for (int i=0; scanner.hasNext(); i++) {
           for(int x=0; x<7 && scanner.hasNext(); x++){
               myStringArray[i][x] = scanner.next();
           }
       }
       System.out.println(Arrays.deepToString(myStringArray));
       scanner.close();
} catch (FileNotFoundException e) {}
于 2013-05-29T18:19:51.010 回答