使用Java扫描程序按顺序从stdin读取时引发异常
作者:互联网
这个问题已经在这里有了答案: > Exception in thread “main” java.util.NoSuchElementException: No line found – Using scanner input 2个
我正在学习如何在Java中使用Scanner,我想从stdin中读取一个整数和一个字符串,因此我编写了以下代码:
import java.util.Scanner;
public class TryScanner {
public void readInt() {
Scanner in = new Scanner(System.in);
System.out.println("Please type in an integer");
int length = in.nextInt();
System.out.println("Integer you type is: " + length);
in.close();
}
public void readString() {
Scanner in = new Scanner(System.in);
System.out.println("Please type in a string");
String s = in.nextLine();
System.out.println("String you type is: " + s);
in.close();
}
public static void main(String[] args) {
TryScanner instance = new TryScanner();
instance.readInt();
// throw exception when called after readInt()
instance.readString();
}
}
我的readInt和readString函数可以分别很好地工作,但是,当我依次调用它们时,只有第一个函数可以工作,第二个则抛出异常:
Please type in an integer
3
Integer you type is: 3
Please type in a string
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1597)
at helloworld.Sort.readString(Sort.java:17)
at helloworld.Sort.main(Sort.java:27)
有人可以解释我做错了什么吗?
解决方法:
删除对
in.close();
当您关闭时,还需要全局关闭System.in(并且不会重新打开).
public void readInt() {
Scanner in = new Scanner(System.in);
System.out.println("Please type in an integer");
int length = in.nextInt();
System.out.println("Integer you type is: " + length);
// in.close();
}
public void readString() {
Scanner in = new Scanner(System.in);
System.out.println("Please type in a string");
String s = in.nextLine();
System.out.println("String you type is: " + s);
// in.close();
}
另外,您可以考虑将扫描仪传递给方法.
public static int readInt(Scanner in) {
System.out.println("Please type in an integer");
return in.nextInt();
}
public static String readString(Scanner in) {
System.out.println("Please type in a string");
return in.nextLine();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Integer you type is: " + readInt(in));
System.out.println("String you type is: " + readString(in));
}
标签:java-util-scanner,stdin,java 来源: https://codeday.me/bug/20191028/1949983.html