Write a program that inputs a sentence from the user assume

Write a program that inputs a sentence from the user (assume no punctuation), then determines and displays the unique words in alphabetical order. Treat uppercase and lowercase letters the same.

Solution

Hi, I assume you want the code in Java. Below is the code I had compiled on CodeChef IDE. I had put the comments along with the code for better understanding.

********************************************************************************************

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be \"Main\" only if the class is public. */
class Codechef
{
   public static void main (String[] args) throws java.lang.Exception
   {
       final String letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";
final int n = letters.length();
  
List<Character> letterList= new ArrayList<Character>();

Random r = new Random();

for (int i = 0; i < 30; i++)
{
letterList.add(letters.charAt(r.nextInt(n))); //to insert random characters
}
  
System.out.println(\"list without sort :\ \"+letterList);
  
Collections.sort(letterList); //sort the list in ascending order
  
System.out.println(\"list after ascending sort :\ \"+letterList);
  
Collections.sort(letterList,Collections.reverseOrder()); //sort the list in descending order
  
System.out.println(\"list after descending sort :\ \"+letterList);
  
//easiest way to remove duplicates.
//introduced in Java 8
letterList = letterList.stream().distinct().collect(java.util.stream.Collectors.toList());
  
Collections.sort(letterList); //sort the list back to ascending order
  
System.out.println(\"list after duplicates removal(in ascending order) :\ \"+letterList);
  
   }
}

********************************************************************************************

OUTPUT:

list without sort :
[V, W, K, J, Z, H, H, P, L, F, R, P, M, B, J, S, B, V, B, L, E, G, O, B, K, P, E, T, N, G]
list after ascending sort :
[B, B, B, B, E, E, F, G, G, H, H, J, J, K, K, L, L, M, N, O, P, P, P, R, S, T, V, V, W, Z]
list after descending sort :
[Z, W, V, V, T, S, R, P, P, P, O, N, M, L, L, K, K, J, J, H, H, G, G, F, E, E, B, B, B, B]
list after duplicates removal(in ascending order) :
[B, E, F, G, H, J, K, L, M, N, O, P, R, S, T, V, W, Z]

let me know if you have any doubts :)

Write a program that inputs a sentence from the user (assume no punctuation), then determines and displays the unique words in alphabetical order. Treat upperca
Write a program that inputs a sentence from the user (assume no punctuation), then determines and displays the unique words in alphabetical order. Treat upperca

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site