简体   繁体   中英

Runtime error. Java. Create a class, Sort that displays four integer numbers in increasing order

I am new in programming, just 1 month. I should create a class, Sort that displays four integer numbers in increasing order. I learned something from here. Unfortunately, this program doesn't run, when compiling there is no error. The error message looks like this:

stderr Exception in thread "main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at Sort.main(Main.java:9)         

Here is program:

import java.util.Scanner;
class Sort
{
    public static void main (String[] args) {
        int a,b,c,d;

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter four numbers: ");
        a = keyboard.nextInt();
        b = keyboard.nextInt();
        c = keyboard.nextInt();
        d = keyboard.nextInt();

        if (a>b) {
            int temp = a;
            a = b;
            b = temp;;
        }
        if (b>c) {
            int temp = b;
            b = c;
            c = temp;
        }
        if (c>d) {
            int temp = c;
            c = d;
            d = temp;
        }
        if (a>b) {
            int temp = a;
            a = b;
            b = temp;
        }
        if (b>c) {
            int temp = b;
            b = c;
            c = temp;
        }
        if (a>b) {
            int temp = a;
            a = b;
            b = temp;
        }
        System.out.println("The numbers :" + a + " " + b + " " + c + " " + d);
    }
}

NoSuchElementException will be thrown if input is exhausted, ie the nextInt() method has no int to return. To fix this you can check if the scanner has more ints with hasNextint() before you call nextInt(). This should get rid of the error, I believe however that this is due to the program not reading all input so maybe should rewrite the input part.

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