问题描述
我在Eclipse Luna中制作了一个简单的Java文字游戏。 Scanner.next()无法正常工作。 运行它时,在询问用户输入后,将显示错误(java.util.NoSuchElementException)。 我刚刚做了一些非常愚蠢的事情吗?
while(whle) {
System.out.print("Where do you want to go? Enter gym, store, or mountain. ");
loc = goTo.next();
loc = loc.toLowerCase();
if(loc.equals("gym") || loc.equals("store") || loc.equals("mountain")) whle = false;
else {
System.out.println("Please enter an option. ");
System.out.println();
}
}
一切都已定义,并且在我运行程序时,在实际程序中没有错误弹出。
1楼
确保您已正确初始化扫描仪
Scanner loc = new Scanner(System.in); //very important
而且您已经导入了该课程
import java.util.Scanner; //in the begining of the source code
它应该可以工作(除此之外,我认为您的IDE(Java版本)有问题)
如果那没有帮助,我自己用该程序运行它(使用boolean whle
初始化, main
方法等),它会产生我认为是您想要的东西。
while(whle) {
System.out.print("Where do you want to go? Enter gym, store, or mountain. ");
String locstring= loc.next();
if(locstring.equalsIgnoreCase("gym") || locstring.equalsIgnoreCase("store") || locstring.equalsIgnoreCase("mountain")){ whle = false;}
else {
System.out.println("Please enter an option. ");
System.out.println();
}
}