0

Good Afternoon I've a piece of code that will count and display the occurrences of each of the letters of the alphabet from user input. But I need to put it in alphabetical order and display the most frequently occurring letter and the number of occurrences for that letter:

package Assessment2;

import java.util.Scanner;

public class test2 {

String str = "Hello World", s = str;
int count = 0;

public void show() {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter String: ");
    String s = input.nextLine();
    System.out.println("****************************");
    while (s.length() > 0) {
        count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == s.charAt(0))
                count++;
        }
        System.out.println(s.charAt(0) + ": " + count);
        s = s.replace(String.valueOf(s.charAt(0)), "");
    }
}

public static void main(String[] ar) {
    new test2().show();
}
}
  • 2
    It looks like your code will loop infinitely while attempting to only count the number of times the first character entered appears in the input. What have you tried to so far to get it sorted and displaying the frequency and count? – Mike B Apr 08 '14 at 14:56
  • Agree with mike B, your code is far from doing what you describe... – Laurent S. Apr 08 '14 at 14:57
  • When it runs I get the following Enter String: kjb jkn **************************** k: 2 j: 2 b: 1 : 1 n: 1 – Chris Stein Apr 08 '14 at 14:59
  • That seems unlikely given that you're never printing anything after you print the ****s. – Mike B Apr 08 '14 at 15:00
  • I tried the sort + Collator, but to no success. @ Mike the result was in the console window on eclipse, I just ran it 5 minutes ago. – Chris Stein Apr 08 '14 at 15:02
  • Possible duplicate: http://stackoverflow.com/questions/15532866/counting-letters-in-a-string-using-two-for-loops – Tdorno Apr 08 '14 at 15:03
  • Sorry Mike just reran it, I must have deleted bits, when working out a solution. – Chris Stein Apr 08 '14 at 15:14

2 Answers2

1

For the part ,you are trying to Sort them by alphabetic order: us the following --for currentChar in a--z --for(loop) each char in inputString --if you encounter any char = currentChar then --append that character to finalstring nd if end loop end for

I have to mention that if you know any sorting algorithms it is better to use that ex: bubble

kiaGh
  • 36
  • 4
0

In order to put the letters in alphabetical order, you need to sort it. You can write your own code to sort the characters of the string or you could use Arrays.sort() to sort an array of characters.

Use char[] charArray = s.toCharArray() to convert the string to a char array and then use Arrays.sort(charArray) to sort the array in alphabetical order.

You can then just loop through the array to find the number of occurrences of each character in the array and then print them.

anirudh
  • 4,116
  • 2
  • 20
  • 35