[英]Scanner doesn't work in multiple methods?
我在構造函數和其他方法中使用了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:掃描儀已關閉
sureOpen(來源不明)
下一個(未知來源)
nextInt(來源不明)
nextInt(來源不明)
在您的“ execute()”方法中,關閉掃描儀
scobj.close();
然后,您執行以下操作:
weekchoice=scobj.nextInt();
一台掃描儀關閉,在其上調用“ nextInt()”將使程序崩潰。
放入“ scobj.close();” 在您的方法結束時,或無論您在何處使用它。
最終看起來像:
public void execute()
{
Scanner scobj=new Scanner(System.in);
String option1;
int weekchoice;
option1=scobj.nextLine();
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;
}
scobj.close();
}
Scanner
關閉后,其內部輸入流System.in
也將關閉。
因此,在調用close()
方法之后,您將無法再訪問它。
從javadoc:
關閉掃描器后,如果源實現了Closeable接口,它將關閉其輸入源。
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
我建議您scObj.close()
在main()
方法的末尾調用scObj.close()
。 然后,您不必再擔心其他方法中的此錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.