for loop problem
Hi all,
I'm having a really weird problem with a for loop iterator that I can't seem to figure out. My program won't iterate over two loops, so I can't add things to a panel. I know how to use for loops so I think it's probably something small, but for some reason I just can't figure it out.
I tried to make this self-containing, hopefully I did it right!
Thanks,
Jezzica85
publicclass ForLoopProblem{
private TreeSet<String> totalUniqueWords =new TreeSet<String>();
private ArrayList<String> allWordsUnsorted =new ArrayList<String>();
private TreeMap<String, Integer> frequencies =new TreeMap<String, Integer>();
/**
* Sets up the frequency list for the rest of the methods
*/
publicvoid frequencySetup(){
// The iterators don't seem to be working...hmmm...
for( String element: totalUniqueWords ){
System.out.println( element );
int frequency = 0;
for( String element2: allWordsUnsorted ){
if( element2.equals( element ) ){
frequency++;
}
}
System.out.println( frequency );
frequencies.put( element, frequency );
}
System.out.println( frequencies );
}
/**
* Shows the frequency of every unique word in all the files
*/
publicvoid allFrequencies(){
// Set up the window
JFrame frequencySub1 =new JFrame("Frequencies of All Words" );
frequencySub1.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
Container pane6 = frequencySub1.getContentPane();
JPanel frequency1 =new JPanel();
frequency1.setLayout(new GridLayout( 0, 2 ) );
Color firstColor =new Color( 255, 102, 255 );
Color secondColor =new Color( 0, 255, 204 );
// Get values from map
Iterator iterator = frequencies.entrySet().iterator();
while( iterator.hasNext() ){
Map.Entry element = ( Map.Entry )iterator.next();
String key = ( String )element.getKey();
JLabel keyLabel =new JLabel( key );
keyLabel.setForeground( Color.BLACK );
keyLabel.setBackground( firstColor );
keyLabel.setOpaque(true );
frequency1.add( keyLabel );
System.out.println("Word added");
Integer value = ( Integer )element.getValue();
String valueString = value.toString();
JLabel valueLabel =new JLabel( valueString );
valueLabel.setForeground( Color.BLACK );
valueLabel.setBackground( secondColor );
valueLabel.setOpaque(true );
frequency1.add( valueLabel );
System.out.println("Value added");
}
// Set up scroll pane
JScrollPane scroller =new JScrollPane( frequency1 );
pane6.add( scroller );
// Finalize window
frequencySub1.setSize( 300, 600 );
frequencySub1.setVisible(true );
}
publicstaticvoid main( String args[] ){
ForLoopProblem problem =new ForLoopProblem();
String word1 = 揳?
String word2 = 揵?
String word3 = 揷?
for(int j = 0, j < 5, j++ ){
allWordsUnsorted.add( word1 );
allWordsUnsorted.add( word2 );
allWordsUnsorted.add( word3 );
}
problem.frequencySetup()
problem.allFrequencies();
}
}
Message was edited by:
jezzica85
Message was edited by:
jezzica85
[5271 byte] By [
jezzica85a] at [2007-10-3 5:15:52]

When you enter the frequencySetup method how many elements are in totalUniqueWords?
Oops, I forgot that when I wrote this out to make it contained. In my actual program it can be anywhere from 300 to 9000 elements.
What do you mean "won't iterate"? Does it compile? Does it throw an exception when running? Does it not work as desired? If the last one, then what should it do and what is it doing instead?
Not its potential size. How many elements are actually in the collection. Add a print statement as the first line that outputs the size.
To PaulCW: What I mean by "won't iterate" is that the code compiles and runs, but it seems like the for loop never gets executed. I put a print statement in the for loop asking it to print out the element and got nothing.
To flounder:
I'll need to edit my code and actually have something add to the totalUniqueWords, I forgot that too (cringes), but the size of it is going to be 3 for this example because the only elements I'm adding are "a", "b", and "c".
OK, here's the class with the edits, hopefully that helps. Oh, and I forgot in my last post, exactly what I want the for loops to do is iterate through totalUniqueWords, if the element matches an element in allWordsUnsorted, increment int frequency, then when it's all the way through allWordsUnsorted concerning that element, add the element and the frequency to a TreeMap. Once that's done, reset frequency to 0 and go to the next element in totalUniqueWords.
Hope that helps,
Jezzica85
public class ForLoopProblem {
private TreeSet<String> totalUniqueWords = new TreeSet<String>();
private ArrayList<String> allWordsUnsorted = new ArrayList<String>();
private TreeMap<String, Integer> frequencies = new TreeMap<String, Integer>();
/**
* Sets up the frequency list for the rest of the methods
*/
public void frequencySetup() {
System.out.println( totalUniqueWords.size() );
// The iterators don't seem to be working...hmmm...
for( String element: totalUniqueWords ) {
System.out.println( element );
int frequency = 0;
for( String element2: allWordsUnsorted ) {
if( element2.equals( element ) ) {
frequency++;
}
}
System.out.println( frequency );
frequencies.put( element, frequency );
}
System.out.println( frequencies );
}
/**
* Shows the frequency of every unique word in all the files
*/
public void allFrequencies() {
// Set up the window
JFrame frequencySub1 = new JFrame( "Frequencies of All Words" );
frequencySub1.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
Container pane6 = frequencySub1.getContentPane();
JPanel frequency1 = new JPanel();
frequency1.setLayout( new GridLayout( 0, 2 ) );
Color firstColor = new Color( 255, 102, 255 );
Color secondColor = new Color( 0, 255, 204 );
// Get values from map
Iterator iterator = frequencies.entrySet().iterator();
while( iterator.hasNext() ) {
Map.Entry element = ( Map.Entry )iterator.next();
String key = ( String )element.getKey();
JLabel keyLabel = new JLabel( key );
keyLabel.setForeground( Color.BLACK );
keyLabel.setBackground( firstColor );
keyLabel.setOpaque( true );
frequency1.add( keyLabel );
System.out.println( "Word added");
Integer value = ( Integer )element.getValue();
String valueString = value.toString();
JLabel valueLabel = new JLabel( valueString );
valueLabel.setForeground( Color.BLACK );
valueLabel.setBackground( secondColor );
valueLabel.setOpaque( true );
frequency1.add( valueLabel );
System.out.println("Value added");
}
// Set up scroll pane
JScrollPane scroller = new JScrollPane( frequency1 );
pane6.add( scroller );
// Finalize window
frequencySub1.setSize( 300, 600 );
frequencySub1.setVisible( true );
}
public static void main( String args[] ) {
ForLoopProblem problem = new ForLoopProblem();
String word1 = 揳?
String word2 = 揵?
String word3 = 揷?
for( int j = 0, j < 5, j++ ) {
allWordsUnsorted.add( word1 );
totalUniqueWords.add( word1 );
allWordsUnsorted.add( word2 );
totalUniqueWords.add( word2 );
allWordsUnsorted.add( word3 );
totalUniqueWords.add( word3 );
}
problem.frequencySetup()
problem.allFrequencies();
}
}
Well in your example you don't add anything to totalUniqueWords and that is why it doesn't enter the loop. Perhaps you should post code that does reproduce what you want.
I just realized that, I fixed it, sorry!
So do you still have a problem or not?
Things are so much easier when you don't mix the UI and the core logic. Then you don't have to wade through UI code to get at the important parts. And you can post test code that's relevant. Etc.
Yes, I still have a problem, sorry if I wasn't clear.
Can you post current code and explain what is/isn't happening and what you expect to happen instead.
OK, I decided to pare down my program and show exactly how it's written and where the problem is. The problem is in the frequencySetup method--the for loops are never accessed.
What I need them to do is--for each element in totalUniqueWords, go over allWordsUnsorted and add one to the frequency if the elements match. After we reach the end of AllWordsUnsorted for each element, add the element and its frequency to a TreeMap. I
know this is long, but I couldn't figure out how to be any clearer.
Thanks,
Jezzica85
public class Problem
private TreeSet<String> totalUniqueWords = new TreeSet<String>();
private ArrayList<String> allWordsUnsorted = new ArrayList<String>();
int index;
private FrequencyListener fListener = new FrequencyListener();
private String fileMined;
/**
* Reads in text files and sets up access to them
*/
public void readFile() {
try {
int startingPoint = numberOfFiles + 1;
// Create button for new file
int fileStart = fileMined.lastIndexOf( "\\" ) + 1;
int fileEnd = fileMined.lastIndexOf( "." );
String fileName = fileMined.substring( fileStart, fileEnd );
JButton button = new JButton( fileName );
button.setForeground( Color.BLACK );
Color mainButtonColor = new Color( 204, 153, 255 );
button.setBackground( mainButtonColor );
numberOfButtons++;
button.addActionListener( listener );
theChapterButtons.add( button );
mainPanel.add( button );
// Read the file and skip the first line
FileReader reader = new FileReader( fileMined );
BufferedReader buffReader = new BufferedReader( reader );
buffReader.readLine();
String line = buffReader.readLine();
StringTokenizer parser = new StringTokenizer( line, " .,?\";:!()厬挀敆\t" );
while( parser.hasMoreTokens() ) {
String next = parser.nextToken();
String finalWord = next.toLowerCase();
allWordsUnsorted.add( finalWord );
totalUniqueWords.add( finalWord );
}
individualChapterLengths.add( chapterAll.size() );
uniqueWordsByChapter.add( chapterUniques.size() );
uniqueListByChapter.add( chapterUniques );
allWords.add( chapterAll );
} catch( Exception e ) {
JOptionPane.showMessageDialog( null, "Restart the application, we have a problem!",
"Undetermined Problem", JOptionPane.WARNING_MESSAGE );
System.exit(-1);
}
}
/**
* The main method.
*
* @param args the command line arguments (ignored)
*/
public static void main( String args[] ) {
try {
fileMined = JOptionPane.showInputDialog( "Input File", "" );
Problem theProgram = new Problem();
problem.readFile();
} catch( Exception e ) {
e.printStackTrace();
System.exit( -1 );
}
}
/**
* An inner class that handles listeners and actions for the frequency window.
*/
class FrequencyListener implements ActionListener {
private TreeMap<String, Integer> frequencies = new TreeMap<String, Integer>();
/**
* Sets up the frequency list for the rest of the methods
*/
public void frequencySetup() {
// The iterators don't seem to be working...hmmm...
for( String element: totalUniqueWords ) {
System.out.println( element );
int frequency = 0;
for( String element2: allWordsUnsorted ) {
if( element2.equals( element ) ) {
frequency++;
}
}
System.out.println( frequency );
frequencies.put( element, frequency );
}
System.out.println( frequencies );
}
/**
* Shows the frequency of every unique word in all the files
*/
public void allFrequencies() {
// Set up the window
JFrame frequencySub1 = new JFrame( "Frequencies of All Words" );
frequencySub1.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
Container pane6 = frequencySub1.getContentPane();
JPanel frequency1 = new JPanel();
frequency1.setLayout( new GridLayout( 0, 2 ) );
Color firstColor = new Color( 255, 102, 255 );
Color secondColor = new Color( 0, 255, 204 );
// Get values from map
Iterator iterator = frequencies.entrySet().iterator();
while( iterator.hasNext() ) {
Map.Entry element = ( Map.Entry )iterator.next();
String key = ( String )element.getKey();
JLabel keyLabel = new JLabel( key );
keyLabel.setForeground( Color.BLACK );
keyLabel.setBackground( firstColor );
keyLabel.setOpaque( true );
frequency1.add( keyLabel );
System.out.println( "Word added");
Integer value = ( Integer )element.getValue();
String valueString = value.toString();
JLabel valueLabel = new JLabel( valueString );
valueLabel.setForeground( Color.BLACK );
valueLabel.setBackground( secondColor );
valueLabel.setOpaque( true );
frequency1.add( valueLabel );
System.out.println("Value added");
}
// Set up scroll pane
JScrollPane scroller = new JScrollPane( frequency1 );
pane6.add( scroller );
// Finalize window
frequencySub1.setSize( 300, 600 );
frequencySub1.setVisible( true );
}
* Handles actions
*
* @param e the event to handle
*/
public void actionPerformed( ActionEvent e ) {
String access = e.getActionCommand();
frequencySetup();
allFrequencies();
}
}
}
Message was edited by:
jezzica85
Message was edited by:
jezzica85
I dont see any for loops in that method.
There's two in the frequencySetup method, those were what I was referring to. Did I have a typo?
Whoops. I was looking in the allFrequencies() method.
*sigh*If only you had posted correct code in the first place we wouldn't have wasted 16 replies.You create a FrequencyListener but you don't add it to anything so no events will be fired and your code won't be executed.
I guess that means I didn't post enough code. I added the frequencyListener to a button in a secondary window that I didn't show in the code I posted. I get the frequency window when I click the button, but it's just a gray box with nothing in it, meaning the for loops aren't working. Should I post the part where I use the frequency listener too? My program is more than 800 lines long overall, I was afraid that would be overkill.
And by the way, I did try to post correct code.
No, we don't want to see 800 lines of code. It's hard since the problem probably occurs in some code you haven't posted but since you have no idea what the problem is you don't know what code to post.
Have you tried some simple debugging. Put print statements in various methods, ie actionPerformed and frequencySetup to make sure these methods are being called. Also, once again make sure there are actually some elements in your TreeSet.
Message was edited by:
flounder
All right, I'll try the print statements again. Thanks for the advice.
Try to make your code very modular, and then test those modules. This is called "unit testing".
So maybe you create one class (or at least, one method) that reads a file. Then you can write a separate test that tests only file reading. Then you can write a method that only does one part of frequency analysis, and then you can write a test that only tests that part.
The great thing about doing things that way, is that you can narrow down problems very easily. You can confirm exactly what's working and what's not, and once you do that you can post only the real problems.
Another thing. You can test your code with "mock objects" or generally dummy data. Suppose you have one class that reads in a dictionary file into, say, a java.util.List, and another class (say, "Foo") that operates on that List. You can write a test that creates a List with dummy data, and use that to test the class Foo. You can create multiple such tests, which multiple versions of dummy data.
This way, you can narrow down the problems even further, and furthermore when you post questions you can show exactly what code is causing problems, and what data is necessary to replicate the problems, without posting thousands of lines of code.
In a couple of places, you have:for( int j = 0, j < 5, j++ ) {That isn't a valid 'for' loop. You have the wrong punctuation.
MLRona at 2007-7-21 10:56:19 >

Correct your for loops like this..for( int j = 0; j < 5; j++ ) { //your code...}Hint: use ; not ,