Home »
Java »
Java Articles
Java program to enter a number and arrange its digits in descending order
By IncludeHelp Last updated : April 7, 2024
Problem statement
Write a Java program to enter a number and arrange its digits in descending order.
Example
Input Number: 76891
Output Number: 98761
Input a number and arrange its digits in descending order
To input a number, you can use the nextInt() method of the Scanner class and to arrange its digits in descending order, use a nested loop where the outer loop will run from 9 to 0 to compare each digit and the inner loop will construct the number from the digits.
Program to enter a number and arrange its digits in descending order in Java
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args) {
// Create a Scanner object to input
Scanner myObj = new Scanner(System.in);
System.out.println("Input an integer number: ");
int number = myObj.nextInt(); // Read integer
int result = 0; // To store sorted number
// sorting the digits in reverese order
for (int i = 9; i >= 0; i--) {
int tempNum = number;
while (tempNum > 0) {
int digit = tempNum % 10;
// Check for the largest digit in
// the given number
if (digit == i) {
result *= 10;
result += digit;
}
tempNum /= 10;
}
}
System.out.println("Input number is: " + number);
System.out.println("Sorted number is: " + result);
}
}
Output
The output of the above program is:
RUN 1:
Input an integer number:
67891
Input number is: 67891
Sorted number is: 98761
RUN 2:
Input an integer number:
123045
Input number is: 123045
Sorted number is: 543210