Java 扫描器输入循环在第一次循环后抛出 No such Element 异常 [英] Java scanner input loop throwing No Such Element exception after first loop

查看:51
本文介绍了Java 扫描器输入循环在第一次循环后抛出 No such Element 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个程序,反复提示用户输入一个数字,然后打印该数字是否为质数.这会起作用一次,然后在下一次迭代中,它会在用户输入另一个输入之前给出 No such Element Exception.

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.

我曾尝试将 IF 语句与 hasNext() 或 hasNextInt() 结合使用,但出于同样的原因,这些语句似乎永远不会成立.我还尝试使用 FOR 循环来迭代固定次数,但这会产生相同的错误.为什么在第一次循环时允许用户输入,但之后不允许?

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();
}

推荐答案

删除 scan.close();,因为它正在关闭扫描仪.

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

这篇关于Java 扫描器输入循环在第一次循环后抛出 No such Element 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆