我不断收到此错误,但我不知道为什么:
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();
然后尝试再次在
takingData
中扫描删除
scan1.close();
之外的takingData
。当您关闭
Scanner
时,正在扫描的InputStream
也将关闭,在这种情况下,您的System.in也将关闭。关闭扫描器后,如果源实现了Closeable接口,它将关闭其输入源。
取自Scanner javadocs