Java Scanner issue - "No Such Element Exception"

3k Views Asked by At

I've read a lot about this problem with scanner object in java. But I've tried some solutions and none gave me a great result.

Here's the deal, I have something like this:

Scanner scan = new Scanner(System.in);
while (!(boolean)) {
    System.out.Println("Please give a char :");
    char c = scan.next().charAt(0);
    [...]
}
scan.close();

And this returns an exception, but I don't have time to type a char:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at class1.main(class.java:21)


I've tried something like this too:

Scanner scan = new Scanner(System.in);
while (!(boolean)) {
    if (scan.hasNextLine) {
        System.out.Println("Please give a char :");
        char c = scan.next().charAt(0);
    }
    [...]
}
scan.close();

But this time, I have an infinite loop :(

I don't get it, I can't figure it out by myself, a lot of solutions I read about don't solve the problem for me.

How can I have my char simply in a loop?

Ps: I apologize for not being perfect in English.

1

There are 1 best solutions below

0
On
scan.next()

is keep enumerating.

So, check before taking input.

Try

    if(scan.hasNext()){

     System.out.Println("Please give a char :");
            char c = scan.next().charAt(0);
            [...]   
   }