Question: Write a program to read in a sentence. Output the sentence and then sort all letters in descending order. Allow users to enter a letter and output the letter with the number of occurrences of that letter, or else indicate that the letter is not found.

Use: "I compute therefore I am"

I've gotten this far with the program:

import java.io.*;
class practicalTest_6{
  public static void main(String args[])throws IOException{
  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input);
  
  System.out.println("Enter a sentence:");
  String sentence = reader.readLine();
  System.out.println("Enter the letter to be searched:");
  String search = reader.readLine();
  
  String upperCase = "";
  
  for(int x = 0; x < sentence.length(); x++){
    if(sentence.substring(x,x+1).equals(" ")){}
    else{upperCase = upperCase + sentence.substring(x,x+1).toUpperCase();}
  }
  
  System.out.println(upperCase);
  }
}

The Final output should look like this:
__________________________________________________________
Input -> I compute therefore I am
All letters in upperCase -> ICOMPUTETHEREFORIAM
Letters in Descending order -> UTTRRPOOMMIIHFEEEECA
Letter to be searched -> E
E occurs 4 times

I have gotten to write it all out in caps, and I can search for occurance of letters but I don't know how to place them a descending order using loops.

Recommended Answers

All 4 Replies

I don't know how to place them a descending order using loops.

You probably need to look at writing a simple bubble sort. Google this to see how it works.
Do you know how to extract all the letters of a String and put them into an array where they are easier to sort? Look at the API doc for the String class. It has methods to help you.

Alternatively...
create an array of 26 ints and use it to count the number of 'A', 'B' ... 'Z' directly. No need to sort then.

?James - place them a descending order?

Yes - if count[c] is the number of occurrences of char c then essentially it's just:

for char c = 'Z' to 'A' descending
   print count[c] copies of char c

and, of course, finding the number of occurrences of a given letter is particularly trivial!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.