PDA

View Full Version : Static error


GreatKhan
06-18-2007, 07:15 AM
Yeah, basically Im getting errors using Iterator itr and ArrayList words in main. Not sure how to fix it up, had this error way back when I was learning java.. shouldnt have taken a break from programing ><

import java.util.*;
import java.io.*;
import javax.swing.*;

public class wordFinder
{
public ArrayList words=new ArrayList();
public Iterator itr;

public static void main(String args[])
{

try
{
FileReader read=new FileReader("C:\x.txt");
BufferedReader readBuffer=new BufferedReader(read);

String word = null;
while (((word=readBuffer.readLine()))!=null)
{
if ((word.length()==5) && (word.endsWith("z")))
words.add(word);
}

readBuffer.close();
}
catch (IOException e) {System.out.println(e);}

try
{
FileWriter write=new FileWriter("C:\xmod.txt");
BufferedWriter writeBuffer=new BufferedWriter(write);


itr = words.iterator();
while ( itr.hasNext ( ) )
{
writeBuffer.write((String)(itr.next()));
writeBuffer.newLine();
}



writeBuffer.close();
}
catch (IOException e) {System.out.println(e);}
}
}

javabits
06-18-2007, 07:48 PM
You should include compiler errors in your description, as people in general are not going to go to the trouble of trying to compile your code.

The variables words and itr are members of the class wordFinder. Your main function cannot access words or itr without an instance to reference

So you would need to create an instance of the class before you could access the variables


public static void main(String args[])
{
wordFinder wf = new wordFinder();
...
...
wf.words.add(word);
...
}


Other options include moving your variable declaration inside of your main function.


public static void main(String args[])
{
ArrayList words=new ArrayList();
Iterator itr;
...
words.add(word);
...

}


or you could make a static reference to the class variables.


public static ArrayList words=new ArrayList();
public static Iterator itr;

public static void main(String args[])
{
...
wordFinder.words.add(word); // the classname in front of words is unnecessary since you are still in the same class but that syntax would be used if you were in a different class
...
}


semper fi...