无论我对代码做什么,nextInt() 中都会出现 NoSuchElementException

问题描述 投票:0回答:1
public class MinimumElement {

public void readIntegers(int userCount) {
    int count = userCount;
    int intArray[] = new int[count];
    Scanner scan = new Scanner(System.in);

    for (int i = 0; i <= count - 1; i++) {
        int number;
        System.out.println("Please input number ");
        number = scan.nextInt();
        intArray[i] = number;
    }
    scan.close();
}

public static void main(String[] Args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the number of elements required for array");
    int userInput = scan.nextInt();
    scan.nextLine();
    scan.close();
    MinimumElement min = new MinimumElement();
    min.readIntegers(userInput);

}

}

也尝试过

hasNextInt
hasNextLine
以及
if
条件。他们总是返回结果值作为
false

java java.util.scanner nosuchelementexception
1个回答
0
投票

好吧,我相信我可能已经找到了解决您问题的方法。问题在于您尝试从

System.in
读取数据的方式:您分配了两个绑定到同一个
Scanner
输入流的
System.in
实例。

int intArray[] = new int[count];
Scanner scan = new Scanner(System.in);

那边:

Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number of elements required for array");

这会引起问题。因此,请创建一个

Scanner
的全局实例,如下例所示。

public class MinimumElement {

    private static Scanner SCANNER;

    public static void main(String[] args) {
        SCANNER = new Scanner(System.in);

        System.out.println("Please enter the number of elements required for array");
        try {
            int userInput = SCANNER.nextInt();
            SCANNER.nextLine();
            MinimumElement min = new MinimumElement();
            min.readIntegers(userInput);
        } finally {
            SCANNER.close();
        }
    }

    public void readIntegers(int userCount) {
        int[] intArray = new int[userCount];
        for (int i = 0; i <= userCount - 1; i++) {
            int number;
            System.out.println("Please input number ");
            number = SCANNER.nextInt();
            intArray[i] = number;
        }
    }
}

请注意,在调用

Scanner
方法后,您必须注意不要与
close()
进行交互,因为这也会导致错误的行为。

© www.soinside.com 2019 - 2024. All rights reserved.