java - 扫描仪混淆错误

标签 java java.util.scanner

我不断收到此错误,但我不知道为什么:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Daily.takingData(Daily.java:33)
at Daily.main(Daily.java:20)

这是我的代码:

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

public class Daily    
{

    private static int size;

    public static void main(String[] args) throws Exception {
        System.out.println("Please enter amount of rows");
        Scanner scan1 = new Scanner(System.in);
        size = scan1.nextInt();
        scan1.close();

        System.out.println();
        takingData(size);
    }

    public static void takingData(int rows) throws Exception {
        System.out.println("Enter 1 To View Number of Markets");
        System.out.println("Enter 2 To View Start and End Dates of Markets");
        System.out.println("Enter 3 To View Start and End Dates of Contracts");
        System.out.println("Enter 4 To View Averages of Markets");
        System.out.println("Enter 0 To Quit Program");
        int choice = 0;
        Scanner scan2 = new Scanner(System.in);
        choice = scan2.nextInt();
        System.out.println("Got here");
        scan2.close();
        if (choice == 0)
            System.exit(0);
    }
} 

我的输出是:

Enter 1 To View Number of Markets
Enter 2 To View Start and End Dates of Markets
Enter 3 To View Start and End Dates of Contracts
Enter 4 To View Averages of Markets
Enter 0 To Quit Program
(error here)

最佳答案

由于您在扫描后立即关闭扫描仪,因此出现错误:

size = scan1.nextInt();
scan1.close();

然后尝试在takeData中再次扫描

删除 takeData 之外的 scan1.close();

当您关闭 Scanner 时,它正在扫描的 InputStream 也会关闭,在这种情况下,您的 System.in 将被关闭。

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

取自 Scanner javadocs

关于java - 扫描仪混淆错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16943874/

相关文章:

java - 如何防止扫描仪接受字符串、负整数或小于 2 的数字?

java - 如何打印没有最后一个逗号的数组字符串?

java - ibm mobilefirst 适配器之间的后调用

java - Spring REST API 中的 Json 模式验证

java - 尝试用 Java 从文件中读取 2 个单词

java - 带枚举的扫描仪,Java

Java 多重扫描器

java - 改进的命名策略 Hibernate 4 不起作用

Java程序接受输入两次

java - 如何使用Scanner检查用户输入是否为整数?