2017-03-06 88 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];