0

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.

Edited by StormHawk: n/a

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0

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.

0

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

0

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!

Edited by JamesCherrill: n/a

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.