我正在 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();
}
}
一切都已定义,当我运行它时,实际程序中不会弹出任何错误。
最佳答案
确保您的扫描仪已像这样正确初始化
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();
}
}
关于java - 设置难度不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497118/