0

So I keep getting the NPException when running my spell checker. The exception occurs in my "edits" method. So here is the code of the method:

    public ArrayList<String> edits (String word){
    ArrayList<String> result = new ArrayList<String>();

    result.add(word.substring(1));
    result.add(word.substring(0, word.length()-1));
    for (char c = 'a'; c <= 'z'; c++){
        result.add(String.valueOf(c) + word);
    }
    for (char c = 'a'; c <= 'z'; c++){
        result.add(word + String.valueOf(c));
    }

    for (int i = 0; i < word.length()-1; i++){
        char[] c = word.toCharArray();
        char temp = c[i];
        c[i] = c[i+1];
        c[i+1] = temp;
        String swappedword = new String(c);
        result.add(swappedword);
    }
    return result;
}

The error occurs at the 4th line, "result.add(word.substring(1));". I have looked at the related answers, but it didn't help me solve the problem. Help please! Thank you all!

5 Answers 5

2
  result.add(word.substring(1));

The only possibility to NPE is your word must be null.

Please take necessary steps regarding that like checking null or informing to method caller by throwing exception.

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

Comments

1

The error occurs at the 4th line, "result.add(word.substring(1));"

Then word must be null. result clearly isn't. You should look at what's calling this code, and work out why it's passing in a null reference. You might also want to add some validation:

public ArrayList<String> edits (String word) {
    if (word == null) {
        throw new NullPointerException();
    }
    ...
}

That way it's immediately clear from the stack trace what's wrong. That's assuming you don't want to accept a null reference, of course - if you do, then just change the code above to return whatever you want. (I'd personally require word to be non-null though.)

Comments

1

In my opinion the Exception occurs because you don't check for word being null.

Comments

0

Try this

public ArrayList<String> edits (String word){
  if (word == null) { 
    return new ArrayList<String>(); // Or null.
  }
  // as before.
}

Comments

0

Check if you word either "" or null

edits("hello");
        edits(""); // fails here java.lang.StringIndexOutOfBoundsException
        edits(null); // fails here  NullPointerException

May be you can add validation in your edit method

if(word==null || word.isEmpty()){
            return  Collections.emptyList();
        }

Comments

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.