简体   繁体   中英

Java scanner input loop throwing No Such Element exception after first loop

I want a program that repeatedly prompts the user to input a number and then prints whether that number is prime or not. This works once, then on the next iteration it gives a No Such Element Exception before the user can enter another input.

I've tried using IF statements with hasNext() or hasNextInt() but those never seem to be true for the same reason. I also tried using a FOR loop to iterate a fixed number of times but that gives the same error. Why is this allowing for user input the first time it loops through but not after that?

public static void primeChecker() 
{ 
      Scanner scan = new Scanner(System.in);
      System.out.print("Please enter a number: ");
      int number = scan.nextInt();
      if (isPrime(number)) {
        System.out.println(number + " is prime");
      }
      else {
        System.out.println(number + " is not prime");
      }
      scan.close();
}

public static void main(String[] args) 
{
    int y=1;
    while(y!=0)
    {
      primeChecker();
}

Remove scan.close(); , as it is closing the scanner.

while (scan.hasNextInt) { int n = scan.nextInt(); ... }

In order to repeatedly ask the user for a number without stopping, you need to put a while around the code.

Here is my take on this challenge:

public static void primeChecker() {

    while(true) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Please enter a number: ");
        int number = scan.nextInt();
        if (isPrime(number)) {
            System.out.println(number + " is prime");
        } else {
            System.out.println(number + " is not prime");
        }
      
    }      
}

public static void main(String[] args) {
    primeChecker();
}

This code should repeatedly ask you for a number(after telling you what the previous answer was). It worked for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM