Reputation: 13
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();
}
}
Upvotes: 0
Views: 1960
Reputation: 36
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
Upvotes: 1
Reputation: 4176
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.
Upvotes: 0