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
麦克洛文

由于没有要求扫描仪在完成从文件中读取后读取用户输入,因此它在询问用户输入号码后仍尝试从文件中读取。您需要创建一个新的扫描仪以从键盘读取。
将以下代码用于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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章