Search code examples
javajava.util.scannernosuchelementexception

Scanner NoSuchElementException in the second iteration of while loop


public static void main(String[] args) {
    while(true)
    {
        System.out.println("Want to repeat :");
        Scanner sc = new Scanner(System.in);
        if(!sc.next().equalsIgnoreCase("y"))
            break;
        //Prime number
        //isPrimeNumber();

        //Fibonacci series
        //fibonacciSeries();

        //factorial using recursion
        getFactorialOfaNumber();

        sc.close();
    }
}

I am having this program, where every time I am checking the input from the console and based on the input provided I am deciding whether to continue or terminate the program.

For the first time it is working fine, but in the second iteration I am getting NoSuchElementException.

Why it is throwing an exception without asking for the input argument.

this is the console output.

y
FACTORIAL
Enter a number:
6
Factorial is :720
Want to repeat :
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at com.chandu.main.PrimeNumbers.main(PrimeNumbers.java:12)

Solution

  • Try to put initialization of a Scanner object outside the while loop, and also the same for the closing instruction like this:

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    
        while(true)
        {
            System.out.println("Want to repeat :");
            if(!sc.next().equalsIgnoreCase("y"))
                break;
            //Prime number
            //isPrimeNumber();
    
            //Fibonacci series
            //fibonacciSeries();
    
            //factorial using recursion
            getFactorialOfaNumber();
        }
        sc.close();
    }
    

    It is not a good idea to create and close scanner every loop. In your case you are also trying to read value from closed System.in which causes a problems