简体   繁体   English

Java 没有此类元素异常扫描仪错误

[英]Java No Such Element Exception Scanner Error

For this code, I'm supposed to ask an integer input from a user and print number is the highest and the lowest.对于此代码,我应该询问用户的 integer 输入,并且打印编号是最高和最低的。 However, on the line where I declare the variable "number" as an int, the console shows the error "java.util.NoSuchElementException".但是,在我将变量“number”声明为 int 的那一行,控制台显示错误“java.util.NoSuchElementException”。 What is wrong with said line?这条线有什么问题?

import java.util.Scanner;

public class MaxMin
{
    public static void main(String[] args)
    {
        int smallest = Integer.MAX_VALUE;
        int largest = 0;
        while(true)
        {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter a number (-1 to quit):");
            int number = input.nextInt();

            if(number >= 0 && number >= largest)
            {
                largest = number;
            }
        
            if(number >= 0 && number <= smallest)
            {
                smallest = number;    
            }
        
            if(number == -1)
            {
                break;    
            }
            System.out.println("Smallest " + smallest);
            System.out.println("Largest " + largest);
        
        }
    }
}

This code is perfectly working fine in my IDE.这段代码在我的 IDE 中运行良好。 However if you enter a large number you will get a different exception like this.但是,如果您输入一个很大的数字,您将得到一个不同的异常,如下所示。 Since integer range is from -2147483648 to 2147483647由于 integer 范围从 -2147483648 到 2147483647

Enter a number (-1 to quit):
21313132313
Exception in thread "main" java.util.InputMismatchException: For input string: "21313132313"
    at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at com.example.demo.Application.main(Application.java:25)

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

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