Exception in thread "main" java.util.NoSuchElementException

Whenever I run this, the function chooseCave()works fine with in.nextInt(). When I select a cave, messages appear at 2-second intervals, and then as soon as it passes this part, it gives me an error:

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

I tried hasNextLine()both hasNextInt(), and when I use while hasNextLine()in the method main, I get more errors. When I use while hasNextInt()in a method chooseCave(), it does not accept my input.

When I use if hasNextInt()in the method chooseCave(), it does not accept my input for the string playAgainand goes directly to another game, but then hasNextInt()boolean returns false, and this is spam "What cave ..." endlessly.

I looked at error reports and Java docs and stack overflows 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();

}

}
+5
source share
6 answers

You close the second Scanner, which closes the base InputStream, so the first Scannercan no longer read from the same results InputStreamand NoSuchElementException.

Decision. For console applications, use one Scannerto read from System.in.

In addition to this: as already mentioned, remember that it Scanner#nextIntdoes not use newline characters. Make sure they were used before calling again nextLinewith Scanner#newLine().

See: Do Not Create Multiple Buffered Wrappers in a Single InputStream

+11
source

nextInt() \n ( ) nextLine(), . , nextLine() :

String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int

, , - "" . nextLine(), int .


, , Scanner, . .


: a String .equals(), ==.

if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time
+6

Reimeus , - in.close selectCave(). , .

if (playAgain == "yes") {
      play = true;
}

equals "==".

if (playAgain.equals("yes")) {
      play = true;
}
+1

in.close() .

0

. , .

NoSuchElementException?

Java . , Enumeration, JDK1.0 , , , Iterator ListIterator.

, Iterator hasNext() , , . hasNext() true, next() . , Iterator remove(), , next().

Although Iterator is generalized for use with all collections in Java Collections Framework, it is ListIteratormore specialized and only works with list-based collections such as ArrayList, LinkedListetc. However, it ListIteratoradds even more functionality, allowing iterations to go both ways with hasPrevious()and previous().

0
source

I have the same error and none of these solutions worked. Try checking the version of Java installed on your PC.

This worked for me in Java 1.8.

-1
source

All Articles