【发布时间】:2018-05-03 19:28:12
【问题描述】:
我在构造函数和另一个方法中使用了 Scanner 类,错误表明 Scanner 已关闭,但我在每个类中创建了两个不同的扫描仪对象。我意识到在方法执行完成后局部变量将被删除(即使在构造函数完成之前调用了execute)但是我认为在每个方法中创建一个对象应该注意这一点?
UserInterface() {
System.out.println("Welcome! Which store would you like to look at?");
Scanner scobj=new Scanner(System.in);
storechoice=scobj.nextInt();
printmenu();
execute();
//scobj.close();
}
public void execute() {
Scanner scobj=new Scanner(System.in);
String option1;
int weekchoice;
option1=scobj.nextLine();
scobj.close();
switch(option1) {
case "a":
System.out.println("Which week?(0-4)");
weekchoice=scobj.nextInt();
f1.getStores(storechoice).totalsalesforweek(weekchoice);
break;
default:
System.out.println("I'm sorry you must choose a-g or q to quit");
break;
}
}
我收到这些错误
IllegalStateException:` 扫描仪已关闭
ensureOpen(未知来源)
下一个(未知来源)
nextInt(未知来源)
nextInt(未知来源)
【问题讨论】:
-
对所有内容使用相同的扫描仪,无需为相同的输入使用多个扫描仪
标签: java methods java.util.scanner