我正在学习如何在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)
有人可以解释我做错的地方吗?
答案 0 :(得分:4)
删除对
的调用array
当您关闭in.close();
时,您还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();
}
传递给方法。
Scanner
答案 1 :(得分:0)
您也可以使用以下代码
import java.util.Scanner;
public class TryScanner {
Scanner in = new Scanner(System.in);
public void readInt() {
System.out.println("Please type in an integer");
int length = in.nextInt();
System.out.println("Integer you type is: " + length);
}
public void readString() {
System.out.println("Please type in a string");
String s = in.nextLine();
System.out.println("String you type is: " + s);
}
public static void main(String[] args) {
TryScanner instance = new TryScanner();
instance.readInt();
instance.readString();
instance.in.close();
}
}