java - 设置难度不起作用

标签 java java.util.scanner

我正在 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/

相关文章:

Java class.getResourceAsStream() 返回不正确的字节

java - 通过Java将HTML内容复制到Excel中

java - 如何使用Java Scanner读取非英文字符?

java - 数组拆分没有给出预期的输出

java - CompletableFuture.runAsync 与 CompletableFuture 数组

java - 继承带有冲突的通用 super 接口(interface)的原始类型

java - 未捕获的 SoapFault 异常 : [soapenv:Server] Before start of result set

java.util.Scanner 没有产生正确的结果

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 从服务器接收数据时出现 NoSuchElementFoundException