Question:
Write a Java program to get the String an input from the user and display the alphabets in the String in descending order.
(Assume all the characters are given in lower case).
Note: In the String “programming” the characters m or r or g is repeated.
Sample input 1:
love
Sample output:
vole
Sample input 2:
programming
Sample output 2:
Rponmiga
Code:
Main.java
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); char ch[] = str.toCharArray(); Arrays.sort(ch); int n = ch.length; for (int i=0;i<n;i++){ for (int j=i+1;j<n;j++) { if (ch[i] == ch[j]) { ch[i] = '*'; } } } String string = ""; for (int i=n-1;i>=0;i--){ if(ch[i]!='*'){ string +=ch[i]; } } System.out.println(string); } }
Output:
programming rponmiga