Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.60/5 (2 votes)
See more:
I want to create a program to display three integer in decreasing order. I did as the following:

Java
import java.util.Scanner;

public class JavaApplication71 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three integers: ");
        int num1 = input.nextInt();
        int num2 = input.nextInt();
        int num3 = input.nextInt();
        
        if ((num1 > num2 && num1 > num3) && (num2 > num3)) {
            System.out.println(num1 + ", " + num2 + ", " + num3);    
        }
        else if ((num1 > num2 && num1 > num3) && (num3 > num2)) {
            System.out.println(num1 + ", " + num3 + ", " + num2);
        }
        else if ((num2 > num1 && num2 > num3) && (num1 > num3)) {
            System.out.println(num2 + ", " + num1 + ", " + num3);
        }
        else if ((num2 > num1 && num2 > num3) && (num3 > num1)) {
            System.out.println(num2 + ", " + num3 + ", " + num1);
        }
        else if ((num3 > num1 && num3 > num2) && (num1 > num2)) {
            System.out.println(num3 + ", " + num1 + ", " + num2);
        }
        else {
            System.out.println(num3 + ", " + num2 + ", " + num1);
        }
        
    }
}


What other ways would I get the same result?

Thank you.
Posted
Comments
Sascha Lefèvre 9-Apr-15 17:25pm    
Instead of that if-else if-cascade you could swap the values of num1/num2/num3 so that they are in descending order and then have a single println-line.
Sascha Lefèvre 9-Apr-15 17:35pm    
As a next step you could read the integers not into separate variables but into either an array or a list (and then sort and print it). That would allow you to handle arbitrarily many values.

1 solution

Store the input in arraylist collection, e.g.
List<integer> list = new ArrayList<integer>();
list.add( num1 );
list.add( num2 );
// ...

then, sort the list in descending refer :http://stackoverflow.com/questions/5894818/how-to-sort-arraylistlong-in-java-in-decreasing-order[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900