-3

I got a task from my university today:

Write a program that reads a ( short ) text from the user and prints the so called max letter (most common character in string) , that the letter which the greatest number of occurrences of the given text . Here it is enough to look at English letters (A- Z) , and not differentiate between uppercase and lowercase letters in the count of the number of occurrences .

For example, if : text = " Ada bada " so should the print show the most common character, this example it would be a.

This is an introductory course, so in this submission we do not need to use the " scanner - class" . We have not gone through this so much. The program will use the show message input two get the text from user .

Info: The program shall not use while loop ( true / false ) , "return " statement / "break " statement .

I've been struggling with how I can get char values into a table.. am I correct I need to use array to search for most common character? I think I need to use the binarySearch, but that only supports int not char.

I'll be happy for any answers. hint's and solutions. etc.. if you're very kind a full working program, but again please don't use the things I have written down in the "info" section above.

My code:

    String text = showInputDialog("Write a short text: "); 

    //format string to char

      String a = text;
      char c = a.charAt(4);
/*with this layout it collects number 4 character in the text and print out.
* I could as always go with many char c... but that wouldn't be a clean program * code.. I think I need to make it into a for-loop.. I have only worked with * *for-loops with numbers, not char (letters).. Help? :) 
*/

    out.print( text + "\n" + c)

//each letter into 1 char, into table
//search for most used letter
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Kel
  • 1
  • 1

3 Answers3

1

Here's the common logic:

  • split your string into chars
  • loop over the chars
  • store the occurrences in a hash, putting the letter as key and occurrences as value
  • return the highest value in the hash

As how to split string into chars, etc., you can use Google. :)

Here's a similar question.

Community
  • 1
  • 1
0

There's a common program asked to write in schools to calculate the frequency of a letter in a given String. The only thing you gotta do here is find which letter has the maximum frequency. Here's a code that illustrates it:

String s <--- value entered by user
char max_alpha=' '; int max_freq=0, ct=0;
char c;
for(int i=0;i<s.length();i++){
    c=s.charAt(i);
    if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
        for(int j=0;j<s.length();j++){
            if(s.charAt(j)==c)
            ct++;
        } //for j
    }
    if(ct>max_freq){
        max_freq=ct;
        max_alpha=c;
    }
    ct=0;
    s=s.replace(c,'*');
}
System.out.println("Letter appearing maximum times is "+max_alpha);
System.out.println(max_alpha+" appears "+max_freq+" times");

NOTE: This program presumes that all characters in the string are in the same case, i.e., uppercase or lowercase. You can convert the string to a particular case just after getting the input.

  • The performance of this algorithm is not the best. You could use a dictionary with each character as the key and the number of occurrences as the value. That complexity is O(n), as opposed to this that is O(n^2). EDIT: I just read lovesmiles07 answer. That is exactly what I am advocating. – BCartolo Mar 11 '16 at 18:30
0

I guess this is not a good assigment, if you are unsure about how to start. I wish you for having better teachers!

So you have a text, as:

String text = showInputDialog("Write a short text: "); 

The next thing is to have a loop which goes trough each letter of this text, and gets each char of it:

for (int i=0;i<text.length();i++) {
    char c=text.charAt(i);
}

Then comes the calculation. The easiest thing is to use a hashMap. I am unsure if this is a good topic for a beginners course, so I guess a more beginner friendly solution would be a better fit.

Make an array of integers - this is the "table" you are referring to. Each item in the array will correspond to the occurrance of one letter, e.g. histogram[0] will count how many "A", histogram[1] will count how many "B" you have found.

int[] histogram = new int[26]; // assume English alphabet only

for (int i=0;i<histogram.length;i++) {
    histogram[i]=0;
}

for (int i=0;i<text.length();i++) {
    char c=Character.toUppercase(text.charAt(i));

    if ((c>=65) && (c<=90)) {
        // it is a letter, histogram[0] contains occurrences of "A", etc.
        histogram[c-65]=histogram[c-65]+1;
    }
}

Then finally find the biggest occurrence with a for loop...

int candidate=0;
int max=0;
for (int i=0;i<histogram.length;i++) {
    if (histogram[i]>max) {
        // this has higher occurrence than our previous candidate
        max=histogram[i];
        candidate=i; // this is the index of char, i.e. 0 if A has the max occurrence
    }
}

And print the result:

System.out.println(Character.toString((char)(candidate+65));

Note how messy this all comes as we use ASCII codes, and only letters... Not to mention that this solution does not work at all for non-English texts.


If you have the power of generics and hashmaps, and know some more string functions, this mess can be simplified as:

String text = showInputDialog("Write a short text: "); 
Map<Char,Integer> histogram=new HashMap<Char,Integer>();

for (int i=0;i<text.length();i++) {
    char c=text.toUppercase().charAt(i));
    if (histogram.containsKey(c)) {
        // we know this letter, increment its occurrence
        int occurrence=histogram.get(c);
        histogram.put(c,occurrence+1);
    }
    else { 
        // we dunno this letter yet, it is the first occurrence
        histogram.put(c,1);
    }
}

char candidate=' ';
int max=0;
for (Char c:histogram.keySet()) {
    if (histogram.get(c)>max) {
        // this has higher occurrence than our previous candidate
        max=histogram.get(c);
        candidate=c; // this is the char itself
    }
}

System.out.println(c);

small print: i didn't run this code but it shall be ok.

Gee Bee
  • 1,754
  • 12
  • 17