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

编程入门 行业动态 更新时间:2024-10-21 13:22:46
本文介绍了Java 扫描器输入循环在第一次循环后抛出 No such Element 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想要一个程序,反复提示用户输入一个数字,然后打印该数字是否为质数.这会起作用一次,然后在下一次迭代中,它会在用户输入另一个输入之前给出 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:24:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128989.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:扫描器   抛出   异常   Java   Element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!