NoSuchElementException二维数组

时间:2014-02-16 04:46:09

标签: java multidimensional-array

我一直得到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

1 个答案:

答案 0 :(得分: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