2017-03-06 91 views
-1

输入数据我想从一个文件,该文件在麻烦从一个文件

1000 
16 11 
221 25 
234 112 
348 102 
451 456 
183 218 
78 338 
365 29 
114 393 
441 369 
531 460 
... 

形式我有麻烦,因为我不断收到IndexOutOfBounds异常或NoSuchElement例外输入数据。如何将数据放入数组中以便日后轻松分类?

public class shortestRoute 
 
{ 
 
\t 
 
    public static void printGrid(int[][] adjMat) 
 
    { 
 
     for(int i = 0; i < 1000; i++) 
 
     { 
 
      for(int j = 0; j < 2; j++) 
 
      { 
 
     \t System.out.printf("%5d", adjMat[i][j]); 
 
      } 
 
      System.out.println(); 
 
     } 
 
    } 
 
\t 
 
    public static void main(String[] args) throws IOException 
 
    { 
 
     File file = new File("rtest1-2.dat"); 
 
     Scanner scanner = new Scanner(file); 
 
     
 
     
 
\t  scanner.useDelimiter("\\s+"); 
 
\t  
 
\t  int N = scanner.nextInt(); 
 
\t  int[][] adjMat = new int[N][2]; 
 

 
\t  for(int i=0; i < N; i++) 
 
\t   for (int j=0; j < 2; j++) 
 
\t    adjMat[i][j] = scanner.nextInt(); 
 
     
 
     printGrid(adjMat); 
 

 
    } 
 

 
}

+0

那么,你得到哪一个 - “IndexOutOfBoundsException”或“NoSuchElementException”?奖金问题:你在哪里得到它们? –

+0

随着上面的代码,我得到一个'IndexOutOfBoundsException'。出于某种原因,它不能正确输入数组。它在输入异常之前只输入40个数据点。 – Nate

+0

代码片段用于JS,而不是Java。停止添加它们。点击“运行代码片段”,并亲自看看它不起作用。 –

回答

1
int N = scanner.nextInt(); 

这将拿起N作为1000 但在给定的例子中,你只有22个整数,而NoSuchElement错误恰好在第22个元素之后。

如果你提供了足够的输入,那么你可以摆脱这个错误。干杯!

2

你迭代得多。您有1000条线,其中有2条Integer,但您要迭代1000x1000条以上Integer。 只需切换内部for循环的2最大:

for(int i=0; i < N; i++){ 
    for (int j=0; j < 2; j++) { 
    adjMat[i][j] = scanner.nextInt(); 
    } 
} 

,你也应该降低您的阵列的配置:

int[][] adjMat = new int[N][2];