# Inputting and sorting three integers

The problem to the question is:

Write a program that takes 3 integers as an input from the user using input dialog messages and sorts the three numbers.

I just want to know: is there any major differences between my code and the book's code in terms of efficiency or anything specific that I could have done better in my code? I am slowly learning Java and am trying to pick up the best techniques as I go along trying to learn this language. Also, I really don't understand the logic behind the book's answer. It seems as if they are only comparing two numbers, but how can they guess what the third number will be in the sort?

Note: I am following my textbook and the newest thing we have learned are if and else statements along with switch statements. I have not learned any looping and I am still in the basics. I am following Introduction To Java Programming 9th edition Daniel Liang and this is from the Chapter 3 exercises.

My solution:

package Chapter3Exercises;
import javax.swing.JOptionPane;

public class SortThreeIntegers
{
public static void main(String[] args)
{
//Prompt user to enter three integers

String stringNum1 = JOptionPane.showInputDialog(null, "Please enter 1st Integer: ");
String stringNum2 = JOptionPane.showInputDialog(null, "Please enter 2nd Integer: ");
String stringNum3 = JOptionPane.showInputDialog(null, "Please enter 3rd Integer: ");

int num1 = Integer.parseInt(stringNum1);
int num2 = Integer.parseInt(stringNum2);
int num3 = Integer.parseInt(stringNum3);

if ((num1 > num2 && num1 > num3))
{
if(num2 > num3)
{
System.out.print(num3 + " " + num2 + " " + num1);
}
else
System.out.print(num2 + " " + num3 + " " + num1);
}
else if ((num2 > num1 && num2 > num3))
{
if(num1 > num3)
{
System.out.print(num3 + " " + num1 + " " + num1);
}
else
{
System.out.print(num1 + " " + num3 + " " + num2);
}
}
else if ((num3 > num1 && num3 > num2))
{
if(num1 > num2)
{
System.out.print(num2 + " " + num1 + " " + num3);
}
else
System.out.print(num1 + " " + num2 + " " + num3);
}
else
{
System.out.println("ERROR!");
}

}

}


Book's solution:

public class Exercise03_08 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);

// Enter three numbers
System.out.print("Enter three integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();

if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}

if (number2 > number3) {
int temp = number2;
number2 = number3;
number3 = temp;
}

if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}

System.out.println("The sorted numbers are "
+ number1 + " " + number2 + " " + number3);
}
}

• Be aware that this is not a real world solution. The simple way to solve this problem is to put the 3 numbers on a List<Integer> then call Collections.sort(myList). – kiwiron Jul 2 '14 at 9:24