简体   繁体   中英

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. However, on the line where I declare the variable "number" as an int, the console shows the error "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. However if you enter a large number you will get a different exception like this. Since integer range is from -2147483648 to 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)

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