Reputation: 109
For a homework assignment I am tasked with determine how many of each letter are in a sentence. I have already successfully completed the homework using JOptionPane. But I want to display in a JFrame. I am able to convert from the text area input, but am no table to convert from string back to text area display.
:
for (short i = 0; i < (output).length(); i++)
{
char temp = Character.toLowerCase((output).charAt(i));
if (temp >= 'a' && temp <= 'z')
counts[temp - 'a']++;
}
for (short i = 0; i < counts.length; i++)
{
output += (char) ('a' + i) + ":\t " + counts[i] + "\n";
}
for (short i = 0; i < (input).length(); i++)
{
if ((output).charAt(i) == 'a' || (output).charAt(i) == 'A')
count++;
}
txaResults.setText(output);
Upvotes: 0
Views: 4006
Reputation: 209072
Try and put the createAndShowGUI
before the frame.setVisible
. You're making the frame visible before your method can perform.
I think this may be your problem:
// You're doing this
output = txaResults.getText();
// but I think you want this
input = txaUserInput.getText();
String output = "";
// Your logic here
...
...
txaResults.setText(output);
You need to perform the logic from the txaUserInput
and display it in the txaResults
Edit: try this for your logic
int[] counts = new int[26];
for (short i = 0; i < (input).length(); i++)
{
char temp = Character.toLowerCase((input).charAt(i));
if (temp >= 'a' && temp <= 'z')
counts[temp - 'a']++;
}
for (short i = 0; i < counts.length; i++)
{
output += (char) ('a' + i) + ":\t " + counts[i] + "\n";
}
int count = 0;
for (short i = 0; i < (input).length(); i++)
{
if ((input).charAt(i) == 'a' || (input).charAt(i) == 'A')
count++;
}
output += "" + count;
txaResults.setText(output);
Upvotes: 1
Reputation: 25028
Use gettext()
to get the text. Then simply loop over the text for words.
You can use a HashMap<String,Integer>
where String
is the word and Integer
is the frequency. When you get the text, just use split()
to break it down into words. Then, loop over it and add each word to the map.
When you add, first check if the word exists. If not, add it and set the count to one. Next time you encounter the word, increment th counter and add it back to the map.
// the horror logic for calculating
// word frequency ommitted for
// sanity's sake
JLabel[] lotOfLabels;
JFrame outputFrame = new JFrame("Final Answer");
Set<String> allMyWords = thatHashMap.keySet();
int totalWords = allMyWords.size();
int count = 0;
outputFrame.setLayout(new FlowLayout());
lotOfLabels = new JLabel[totalWords];
for(String each : allMyWords){
int frequencyOfAWord = allMyWords.get(each);
lotOfLabels[count] = new JLabel(each + " " + frequencyofAWord);
outputFrame.getContentPane().add(lotsOfLabels[count]);
count++;
}
outputFrame.pack();
outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outputFrame.setVisible(true);
The code above is for showing the answer in a JFrame
Upvotes: 0