Question:
How do I do the following:
A user will input 3 different numbers and the program should return a 3-digit number in ascending order of the digits.
For example, if the user inputs 6, 1, 5 the returned integer should be 156.
A user will input 3 different numbers and the program should return a 3-digit number in ascending order of the digits.
For example, if the user inputs 6, 1, 5 the returned integer should be 156.
Answer:
Put the three numbers in a array. Use the method Arrays.sort() to sort them. Then a little math to get to the final number.
Code:
import java.util.*; public class SortNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] input = new int[3]; System.out.print("Enter Number: "); input[0] = sc.nextInt(); System.out.print("Enter Number: "); input[1] = sc.nextInt(); System.out.print("Enter Number: "); input[2] = sc.nextInt(); System.out.println("Before: " + Arrays.toString(input)); Arrays.sort(input); System.out.println("After: " + Arrays.toString(input)); int number = input[0]*100; number = number + (input[1]*10); number = number + input[2]; System.out.println("Number: " + number); } }
Output:
$ java SortNumbers Enter Number: 6 Enter Number: 1 Enter Number: 5 Before: [6, 1, 5] After: [1, 5, 6] Number: 156