-2

If user input 3 numbers in any order. How do I code in Java so that it displays the largest number first to the smallest number last. My logic is so: Take every number and subtract it from the other numbers. When subtract if result is positive tally qty of positive per number. The number with must positive tally is Largest, and so on. The question is is this logic code-able in Java or is there a better method than my logic?

User input these 3 numbers: 5 , 3, 7 (n1, n2, n3)

1st vs. 2nd
5-3= 2  (positive}   <----2nd winner
3-5= -2 

1st vs. 3rd
5-7 =-2
7-5 = 2 (positive)  <-----winner

2nd vs. 3rd
3-7= -4
7-3 = 4 (positive)   <--------winner
FreedomPride
  • 1,098
  • 1
  • 7
  • 30
Hunter
  • 15
  • 3
  • Add the number to a list and sort the list? – David Feb 16 '17 at 01:26
  • I'd add them to an array and call `Arrays.sort` so it sorts three these numbers. As for your suggestion: I'd avoid subtracting numbers as `a > b` is much more readable than `a - b > 0`, and you probably don't have to do anything with the differences other than comparing them to zero. – yeputons Feb 16 '17 at 01:47

2 Answers2

0

You can simply use if condition to check bigger number

Here's a sample program

import java.util.*;
public class SortNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three integers: ");
int x = sc.nextInt();
int y = sc.nextInt(); 
int z = sc.nextInt(); 
if (x < y) {
int temp = x;
x = y;
y = temp;
}
if (y < z) {
int temp = y;
y = z;
z = temp;
}
if (x < y) {
int temp = x;
x = y;
y = temp;
}
System.out.println("The sorted numbers are " + x + "," + y + "," + z);
}
}
0

When the user inputs the numbers, add them to a arrayList

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(input1);
numbers.add(input2);
numbers.add(input3);

Then use the sort method from Arrays:

Collections.sort(numbers);
Ryan
  • 1,972
  • 2
  • 23
  • 36