0

I have a WordFreq class that has a processLines method that creates an array from the WordCount class. I have other lines of the processLines method access WordCount without an issue.

I have:

public class WordCount{

    private String word;
    private int count;

    public WordCount(String w){
        word = w;
        count = 0;
    }

followed by the class methods:

public class WordFreq extends Echo {

    String words, file;
    String[] wordArray;
    WordCount[] search;

WordFreq is passed a text file(handled in Echo) and a string of words to search for.

public WordFreq(String f, String w){
    super(f);
    words = w;
}

public void processLine(String line){
    file = line;
    wordArray = file.split(" ");

    // here is where I have tried several methods to initialize the search
    // array with the words in the words variable, but I can't get the
    // compiler to accept any of them.

    search = words.split(" ");

    StringTokenizer w = new StringTokenizer(words);
    search = new WordCount[words.length()];

    for(int k =0; k < words.length(); k++){
        search[k] = w.nextToken();

I tried a few other things that didn't work. I tried casting what was to the right of search[k] = to WordCount, but it won't get past the compiler. I keep getting incompatible types.

Required: WordCount found: java.lang.String. 

I have no idea where to go from here.

1
  • 1
    For better help sooner, post an SSCCE. Commented Apr 17, 2013 at 3:45

1 Answer 1

1

Try something like this:

String[] tokens = words.split(" ");
search = new WordCount[tokens.length];
for (int i = 0; i < tokens.length; ++i) {
    search[i] = new WordCount(tokens[i]);
}

The problem with your first attempt is that words.split(" ") results in a String array; you can't assign to a WordCount array variable. The problem with the second method is that words.length() is the number of characters in words, not the number of tokens. You could probably make your second method work by using w.countTokens() in place of words.length(), but, again, you need to convert each String returned by w.nextToken() to a WordCount object.

Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick! I ended up with some run time errors using the .length() in some other methods. I probably would have gotten stuck there for a little bit if you hadn't pointed that out. I've got the program functioning properly now. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.