线程“main"中的异常java.util.NoSuchElementException [英] Exception in thread "main" java.util.NoSuchElementException

查看:27
本文介绍了线程“main"中的异常java.util.NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我运行它时,chooseCave() 函数与 in.nextInt() 一起工作得很好.当我选择洞穴时,消息以 2 秒的间隔弹出,然后一旦它通过那部分,它就会给我错误:

Whenever I run this, the chooseCave() function works fine with the in.nextInt(). When I choose the cave, the messages pop up at 2-second intervals, and then as soon as it gets past that part, it gives me the error:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Dragon.main(Dragon.java:81)

我尝试过 hasNextLine()hasNextInt(),当我在 main<中使用 while hasNextLine() 时/code> 方法,我收到了更多错误.当我在 chooseCave() 方法中使用 while hasNextInt() 时,它不接受我的输入.

I have tried hasNextLine() and hasNextInt(), and when I use while hasNextLine() in the main method, I get a ton more errors. When I use while hasNextInt() in the chooseCave() method, it doesn't accept my input.

当我在 chooseCave() 方法中使用 if hasNextInt() 时,它不接受我对 playAgain 字符串的输入,然后直接进入另一个游戏,但是 hasNextInt() 布尔值返回 false 并且它无限地发送Which Cave...".

When I use if hasNextInt() in the chooseCave() method, it doesn't accept my input for the playAgain string, and goes straight into another game, but then the hasNextInt() boolean returns false and it spams "Which cave..." infinitely.

我已经浏览了错误报告以及 Java 文档和 Stack Overflow 的类似问题.请帮忙.

I've gone through the error reports and the Java-docs and Stack Overflow's with similar problems. Please help.

import java.util.Scanner;
public class Dragon {

public static void displayIntro() {
    System.out.println("You are in a land full of dragons. In front of you, ");
    System.out.println("You see two caves. In one cave, the dragon is friendly");
    System.out.println("and will share his treasure with you. The other dragon");
    System.out.println("is greedy and hungry, and will eat you on sight");
    System.out.println(' ');
}

public static int chooseCave() {
    Scanner in = new Scanner(System.in);
    int cave = 0;
    while (cave != 1 && cave != 2) {
        System.out.println("Which cave will you go into? (1 or 2)");

        cave = in.nextInt();

    }
    in.close();
    return cave;
} 

public static void checkCave(int chosenCave) {
    System.out.println("You approach the cave...");
    try
       {
       // Sleep at least n milliseconds.
       // 1 millisecond = 1/1000 of a second.
       Thread.sleep( 2000 );
       }
    catch ( InterruptedException e )
       {
       System.out.println( "awakened prematurely" );
       }
    System.out.println("It is dark and spooky...");
    try
       {
       // Sleep at least n milliseconds.
       // 1 millisecond = 1/1000 of a second.
       Thread.sleep( 2000 );
       }
    catch ( InterruptedException e )
       {
       System.out.println( "awakened prematurely" );
       }
    System.out.println("A large dragon jumps out in front of you! He opens his jaws and...");
    try
       {
       // Sleep at least n milliseconds.
       // 1 millisecond = 1/1000 of a second.
       Thread.sleep( 2000 );
       }
    catch ( InterruptedException e )
       {
       System.out.println( "awakened prematurely" );
       }

    double friendlyCave = Math.ceil(Math.random() * 2);

    if (chosenCave == friendlyCave) {
        System.out.println("Gives you his treasure!");
    }
    else {
        System.out.println("Gobbles you down in one bite!");
    }



}
public static void main(String[] args) {
    Scanner inner = new Scanner(System.in);
    String playAgain = "yes";
    boolean play = true;
    while (play) {
        displayIntro();
        int caveNumber = chooseCave();
        checkCave(caveNumber);
        System.out.println("Do you want to play again? (yes or no)");
        playAgain = inner.nextLine();
        if (playAgain == "yes") {
            play = true;
        }
        else {
            play = false;
        }
    }
    inner.close();

}

}

推荐答案

你关闭了第二个 Scanner,它关闭了底层的 InputStream,因此第一个 Scanner 无法再从相同的 InputStreamNoSuchElementException 结果中读取.

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

解决方案:对于控制台应用程序,使用单个 ScannerSystem.in 读取.

The solution: For console apps, use a single Scanner to read from System.in.

旁白: 如前所述,请注意 Scanner#nextInt 不消耗换行符.确保在使用 Scanner#newLine() 再次尝试调用 nextLine 之前消耗了这些.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

参见:不要在单个 InputStream 上创建多个缓冲包装器

这篇关于线程“main"中的异常java.util.NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆