Big_Chair
Big_Chair

Reputation: 3239

noSuchElement exception with nextInt() method

Hey guys I don't get why I get an exception in this simple code
I'm trying to make a card game, and try to read the users wanted index of the card in his hand (it's in German)

public Karte abschlagen(Karte gegnK) {
    System.out
            .println("Bitte die Zahl für die jeweilige Karte auswählen: ");
    gibHandAus(); // prints the users cards with their indexes 

    try {
        Scanner sc = new Scanner(System.in);
        int index = sc.nextInt();
        if (index < 0 || index >= getHand().size()) {
            System.out
                    .println("Bitte nur eine der gegebenen Zahlen auswählen!");
                     sc.close();
            return abschlagen(gegnK);
        }
        Karte k = getHand().get(index);
        getHand().remove(index);
        sc.close();

So what's the problem here?
Before I can choose a number, it throws the noSuchElement exception.
I read in another question that the close() method can be causing this, but it still did it without it.

The error message is:

Exception in thread "main" java.util.NoSuchElementException
   at java.util.Scanner.throwFor(Unknown Source) 
   at java.util.Scanner.next(Unknown Source) 
   at java.util.Scanner.nextInt(Unknown Source) 
   at java.util.Scanner.nextInt(Unknown Source) 
   at durak.Spiel.spielerWehrtAb(Spiel.java:229) 
   at durak.Spiel.main(Spiel.java:314) 

EDIT: Code of spielerWehrAb():

public static boolean spielerWehrtAb(Karte k) {
.
.
.
try {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();

if (x == 0) {
... }
else if(x == 1) {
System.out.println("1 ausgewählt");
Karte k2 = spieler.abschlagen(k);
....
} 
else return spielerWehrAb(k);

Upvotes: 1

Views: 366

Answers (1)

RGO
RGO

Reputation: 4737

The problem is Scanner.close(); closes the underlying stream. The second time, you're trying to read from a closed stream, so it obviously fails.

Please see the tests I designed to demonstrate this behavior here: java.util.Scanner strange behaviour when used with System.in

The solution would be not to read after closing the Scanner. You could, for example, define the Scanner as a class member and always use that member.

Upvotes: 1

Related Questions