简体   繁体   English

Java 扫描仪输入循环在第一次循环后抛出 No such Element 异常

[英]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.我尝试过将 IF 语句与 hasNext() 或 hasNextInt() 一起使用,但出于同样的原因,这些语句似乎从来都不是真的。 I also tried using a FOR loop to iterate a fixed number of times but that gives the same error.我还尝试使用 FOR 循环来迭代固定次数,但这会产生相同的错误。 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();删除scan.close(); , as it is closing the scanner. ,因为它正在关闭扫描仪。

while (scan.hasNextInt) { int n = scan.nextInt(); 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.为了不断地向用户询问数字,您需要在代码周围放置一段while

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!它对我有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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