简体   繁体   中英

Sort an amount of user entered numbers according to size (Java)

I'm trying to figure out how to sort a user defined number of user defined numbers according to size, the user defined numbers are doubles.

I'm trying to do it without using arrays or anything too complex, ideally using some form or combination of Math.min and Math.max

eg

int lowestNumber = (int)Math.min(firstNumber, (Math.min(secondNumber, Math.min(thirdNumber, finalNumber) )));

This gets me the lowest number, that's fine, but when i try and do

int secondLowestNumber = (int)Math.min(lowestNumber, firstNumber,(Math.min(secondNumber, Math.min(thirdNumber, finalNumber))));

I get the lowest number again. I guess the problem is that I don't know how to eliminate the lowest number once I've completed the first assignment.

Just to summarize the comments on your original question:

You can sort using an ArrayList very easily using Collections.sort(). Here's an example:

    //lets say we have these three numbers:
    int num1 = 2, num2 = 5, num3 = 3;

    List<Integer> list = new ArrayList<Integer>();
    list.add(num1);
    list.add(num2);
    list.add(num3);

    System.out.println(list);

    Collections.sort(list);

    System.out.println(list);

The above results in the output:

[2, 5, 3]
[2, 3, 5]

As expected!

Note we can generalize this using for loops to add more numbers or use other primitive numbers than ints... Let me know if you need other details!

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