2014-02-16 144 views
0

我不斷收到NoSuchElementException,但我不知道爲什麼。我知道錯誤是掃描儀,但不知道這個錯誤發生的原因。我包括輸入文件。NoSuchElementException二維數組

import java.util.*; 
import java.io.*; 

public class Numbrosia { 
    static int [][] board = new int [5][5]; 
    public static void main(String[]args){ 
     Scanner scan = null; 
     try{ 
      scan = new Scanner(new File("input.txt")); 
     } 
     catch(FileNotFoundException e){ 
      e.printStackTrace(); 
      return; 
     } 
     for(int row = 0; row<board.length; row++){ 
      for(int col= 0; col<board.length;col++){ 
       board[row][col] = scan.nextInt(); 
      } 
     } 
    while(true){ 
        showBoard(); 
        System.out.println(""); 
        System.out.println("Input number from 1 to 5: "); 
        int i = scan.nextInt(); 
        System.out.println("Input move command: "); 
        String moveName = scan.next(); 
        //If/ else statements to dictate which method to call 

錯誤消息:

Exception in thread "main" java.util.NoSuchElementException 
    at java.util.Scanner.throwFor(Scanner.java:838) 
    at java.util.Scanner.next(Scanner.java:1461) 
    at java.util.Scanner.nextInt(Scanner.java:2091) 
    at java.util.Scanner.nextInt(Scanner.java:2050) 
    at excercises.Numbrosia.main(Numbrosia.java:25) 

輸入文件:

1 -2 1 0 0 
-1 0 4 2 0 
0 -4 1 -1 0 
0 1 -1 -1 -2 
0 -3 1 -1 0 
+0

你能發表更多的代碼嗎? –

+0

在循環的第一次迭代中拋出異常嗎? – McLovin

+0

我剛剛發佈了更多代碼 – user124557

回答

1

由於掃描儀沒有被告知讀取用戶輸入其完成從文件中讀取後,它仍然在努力在向用戶索要號碼之後從文件中讀取數據。您需要創建一個新的掃描儀從鍵盤讀取。
使用下面的代碼爲while循環:

scan.close(); 
Scanner kbScan = new Scanner(System.in); 
while(true){ 
    showBoard(); 
    System.out.println(""); 
    System.out.println("Input number from 1 to 5: "); 
    //This will read from the keyboard 
    int i = kbScan.nextInt(); 
    System.out.println("Input move command: "); 
    String moveName = scan.next(); 

中,你需要從鍵盤讀取方法在別的地方,使用kbScan代替scan