简体   繁体   English

NoSuchElementException二维数组

[英]NoSuchElementException 2-d array

I keep getting NoSuchElementException but I'm not sure why. 我一直收到NoSuchElementException,但不知道为什么。 I know the error is for the scanner but don't know the reason this error is happening. 我知道错误是针对扫描仪的,但不知道发生此错误的原因。 I included the input file. 我包括了输入文件。

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

Error Message: 错误信息:

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)

Input file: 输入文件:

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

Because your scanner is not being told to read user input after it finishes reading from the file, It is still trying to read from the file after it asks the user for a number. 由于未告知扫描仪在完成从文件中读取后读取用户输入,因此它在询问用户输入号码后仍尝试从文件中读取。 You need to create a new Scanner to read from the keyboard. 您需要创建一个新的扫描仪以从键盘读取。
Use the following code for the while loop: 将以下代码用于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();

Anywhere else in the method that you need to read from the keyboard, use kbScan instead of scan . 在需要从键盘读取的方法中的其他任何地方,请使用kbScan而不是scan

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM