我是 Java 新手,我正在尝试从键盘读取数据,但遇到异常,我不知道为什么以及如何修复它。
导入java.util.Scanner;
public class Test {
public static void main(String[] args) {
Test r = new Test();
System.out.println("Type a int number : " + r.readInteger());
System.out.println("type a double number: " + r.readDouble());
}
public int readInteger() {
Scanner input = new Scanner(System.in);
int val = 0;
while(true) {
if(input.hasNextInt()) {
val = input.nextInt();
input.nextLine();
break;
}
else {
System.out.println("Invalid data type.");
input.nextLine();
}
}
input.close();
return val;
}
double readDouble() {
Scanner input = new Scanner(System.in);
double val = 0;
while(true) {
if(input.hasNextDouble()) {
val = input.nextDouble();
input.nextLine();
break;
}
else {
System.out.println("Invalid data type.");
input.nextLine();
}
}
input.close();
return val;
}
}
异常(exception):
[roger@archroger ~]$ java Test
3
Type a int number : 3
Invalid data type.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Test.readDouble(Test.java:44)
at Test.main(Test.java:8)
最佳答案
当输入流为System.in
时,不要关闭扫描仪。这也将关闭标准输入,并且当您不检查该行是否存在时,像 scanner.nextLine()
这样的语句将抛出 NoSuchElementException
。您使用 scanner.hasNextInt()
检查是否有另一个整数标记可用,然后尝试使用 scanner.getNextLine()
获取另一行,而不测试该行是否存在。使用scanner.hasNextLine()。
关于java - 从键盘读取数据时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50567995/