我不断收到此错误,但我不知道为什么:
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.
关于java - 扫描仪混淆错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16943874/