0

So I cannot seem to figure out why I am unable to assign the new values to the String[] fileWords in my collectWords method. If i do it outside of the for loop.

Say fileWords[1] = "Hello", this works. However the same type of assignment in my for loop does not. This ultimately ensures i run into a null pointer exception (Code may have the odd little syntax error as I am still testing some of the methods).

To clarify this is a homework assignment and we have to use standard arrays as that is the instruction (Memory allocation related practice).

Basically what the code does it grab words from a txt file and must then count the number of words of n length and add it to the array. The length of the words is supposed to be correlated to the index number. Personally feels like there will be a lot array null values but hey this is what we have been instructed to do.

Code:

import edu.duke.*;
import org.apache.commons.csv.*;
import java.util.*;
import java.io.*;

public class WordLengths{
    public static void main(String args[]){
            WordLengths wordLengths = new WordLengths();
            wordLengths.testCountWordLengths();
    }
    
    private Integer countWordsInFile(FileResource fr){
            int nWords = 0;
            for(String s : fr.words())
            {
                    nWords++;
            }
            System.out.println("Number of words in file: "+ nWords);
            return nWords;
    }
    private String[] collectWords(FileResource fr)
    {
            int nWords = countWordsInFile(fr);
            String[] fileWords = new String[nWords+1];
            int i = 0;
            for(String s : fr.words())
            {
                    fileWords[i] = s;
                    i++;
                    System.out.println("fileWords: "+i+ " word: " + fileWords[i]);
            }
            return fileWords;
    }
    private void testCollectWords(){
            FileResource fr = new FileResource();
            String[] wordCollection = collectWords(fr);
            System.out.println("Word collection: "+wordCollection);
    }
}

Example of .txt file input:

THE TRAGEDY OF JULIUS CAESAR

by William Shakespeare



Dramatis Personae

JULIUS CAESAR, Roman statesman and general
OCTAVIUS, Triumvir after Caesar's death, later Augustus Caesar,
first emperor of Rome
MARK ANTONY, general and friend of Caesar, a Triumvir after his death
LEPIDUS, third member of the Triumvirate
MARCUS BRUTUS, leader of the conspiracy against Caesar
CASSIUS, instigator of the conspiracy
CASCA,          conspirator against Caesar
TREBONIUS,           "          "     "
CAIUS LIGARIUS,      "          "     "
DECIUS BRUTUS,       "          "     "
METELLUS CIMBER,     "          "     "
CINNA,               "          "     "
CALPURNIA, wife of Caesar
PORTIA, wife of Brutus
CICERO,     senator
POPILIUS,      "
POPILIUS LENA, "
FLAVIUS, tribune
MARULLUS, tribune
CATO,     supportor of Brutus
LUCILIUS,     "     "    "
TITINIUS,     "     "    "
MESSALA,      "     "    "
VOLUMNIUS,    "     "    "
ARTEMIDORUS, a teacher of rhetoric
CINNA, a poet
VARRO,     servant to Brutus
CLITUS,       "    "     "

To clarify my current algo does not accomodate for words that are next to , " and so forth (baring words such as isn't, etc).

Any suggestions would be great. Additionally any alternative recommendations for values I can assign to the index numbers that end up having no words of n length. The code will explain why there would be 0 as values (Must still add that part but cannot get it to assign any values right now for clarity).

Thanks.

3
  • 1
    please create a minimal-reproducible-example Commented Apr 30, 2022 at 10:23
  • @TmTron , I think that is as minimal as I can get it without writing a completely different method. Commented Apr 30, 2022 at 10:37
  • @NotReallyOliverTwist that's one of the advantages of a minimal reproducible example, you narrow the problem down to a specific method, instead of a (non-compiling) code dump, possibly better understanding (if not flat out solving) the problem yourself in the process. Also you may want to point out what you expected your code to show and what it shows instead. Commented Apr 30, 2022 at 10:58

1 Answer 1

1

Your problem is in method collectWords. You are using the wrong index to print the word. Here is your code for method collectWords:

private String[] collectWords(FileResource fr) {
    int nWords = countWordsInFile(fr);
    String[] fileWords = new String[nWords + 1];
    int i = 0;
    for (String s : fr.words()) {
        fileWords[i] = s;
        i++;
        System.out.println("fileWords: " + i + " word: " + fileWords[i]);
    }
    return fileWords;
}

In the first iteration of the for loop, the value of i is 0 (zero). You store a word in array fileWords at index 0. Then you increment the index so the value of i is now 1 (one). The element in fileWords at index 1 is [still] null. The fix with the least changes is to change the line:

System.out.println("fileWords: " + i + " word: " + fileWords[i]);

to:

System.out.println("fileWords: " + i + " word: " + fileWords[i - 1]);

Also, you cannot simply print the contents of an array. Again, the simplest way to print the contents of an array (in my opinion) is via method toString in class java.util.Arrays. Hence the last line of method testCollectWords should be:

System.out.println("Word collection: " + Arrays.toString(wordCollection));

Here is your code with my corrections.

public class WordLengths {
    private Integer countWordsInFile(FileResource fr) {
        int nWords = 0;
        for (String s : fr.words()) {
            nWords++;
        }
        System.out.println("Number of words in file: " + nWords);
        return nWords;
    }

    private String[] collectWords(FileResource fr) {
        int nWords = countWordsInFile(fr);
        String[] fileWords = new String[nWords + 1];
        int i = 0;
        for (String s : fr.words()) {
            fileWords[i] = s;
            i++;
            System.out.println("fileWords: " + i + " word: " + fileWords[i - 1]);
        }
        return fileWords;
    }

    private void testCollectWords() {
        FileResource fr = new FileResource();
        String[] wordCollection = collectWords(fr);
        System.out.println("Word collection: " + java.util.Arrays.toString(wordCollection));
    }

    public static void main(String[] args) {
        WordLengths wordLengths = new WordLengths();
        wordLengths.testCollectWords();
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

OMG, that was such a simple thing. Will do what you mentioned though. I feel really dumb now. Shall I just delete this post instead? :D
@NotReallyOliverTwist I discovered it by stepping through your code with the debugger of my IDE. Every programmer needs to learn how to debug his code.
definitely noted. Still on the learning curve, I was using Vim and not an IDE. It is something on my list though so thanks for that heads up too!

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.