我对此代码的解决方案是在GetInput类中创建一个Scanner对象,并且只创建一个Scanner(System.in)实例,并在完成后关闭它一次。
我的问题是为什么下面的代码不起作用?我完成后关闭扫描仪对象,并在我希望再次阅读时决定打开一个新的扫描仪对象。
此代码在收到第一个输入后抛出的异常是NoSuchElementException。
为什么同一个物体上的扫描仪可以多次打开和关闭?
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GetInput {
public static int getInputFirstTime(){
Boolean isNumber = false;
Scanner sc = new Scanner(System.in);
String input = "";
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex);
System.out.println("Please Enter a Number");
while (!isNumber){
try {
input = sc.next();
Matcher matcher = pattern.matcher(input);
if (matcher.matches() == true){
isNumber = true;
}
if(!isNumber) { System.out.println("Please enter only digits: ");}
}
catch (Exception e){
System.out.println(e.toString());
}
}
sc.close();
return Integer.parseInt(input);
}
public static int getInputSecondTime(){
Boolean isNumber = false;
Scanner sc = new Scanner(System.in);
String input = "";
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex);
System.out.println("Please Enter a Number");
while (!isNumber){
try {
input = sc.next();
Matcher matcher = pattern.matcher(input);
if (matcher.matches() == true){
isNumber = true;
}
if(!isNumber) { System.out.println("Please enter only digits: ");}
}
catch (Exception e){
System.out.println(e.toString());
}
}
sc.close();
return Integer.parseInt(input);
}
public static void main(String[] args) {
int one = getInputFirstTime();
int two = getInputSecondTime();
System.out.println("one: " + one);
System.out.println("two: " + two);
}
}