Question:

Someone please help with my JAVA program

by Guest63136  |  earlier

0 LIKES UnLike

I'm suppose to create a program that counts the number of occurences of each letter of the alphabet in a string. And the program needs to print out the letters in order of their frequencey, from most frequent to least frequent. And I need to only print out letters that appear in the text. And I need to print out the count of each letter with the letter - if two letters have an equal number of occurences it doesnt matter what order you print them in.

This is what I've got so far:

import javax.swing.JOptionPane;

public class CountEachLetter {

/** Main method */

public static void main(String[] args) {

// Prompt the user to enter a string

String s = JOptionPane.showInputDialog("Enter a string:");

// Invoke the countLetters method to count each letter

int[] counts = countLetters(s.toLowerCase());

// Declare and initialize output string

String output = "";

// Display results

for (int i = 0; i < counts.length; i ) {

if (counts[i] != 0)

output = (char)('a' i) " appears "

counts[i] ((counts[i] == 1) ? " time\n" : " times\n");

}

// Display the result

JOptionPane.showMessageDialog(null, output);

}

// Count each letter in the string

public static int[] countLetters(String s) {

int[] counts = new int[26];

for (int i = 0; i < s.length(); i ) {

if (Character.isLetter(s.charAt(i)))

counts[s.charAt(i) - 'a'] ;

}

return counts;

}

}

What else am i missing? I just can't figure it out.

Thanks for the help everyone

 Tags:

   Report

1 ANSWERS


  1. Looks pretty good so far.

    You will need to sort the array after you are finished counting letters; take a look at Arrays.sort(int[]). You also are going to get an ArrayIndexOutOfBoundsException if the character is anything but lower case a-z, because Character.isLetter(char) returns true for upper case, lower case, and a few other categories of characters.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions