Search code examples
javastringclassfor-loopmethods

Error when calling ".length" method on instance variable


I made a quite simple class (boils down to a guessing game) and when I tried to run my code a "error: cannot find symbol" keeps popping up whenever I call the ".length" method on my instance variable.

instance variable:

 private String word;

methods where the error keeps appearing:

private String inWord(String str, int index)
{
        if(str.equals(word.substring(index, index + 1)))
            return str;
        else
        {
            for(int i = 0; i < word.length; i++)
            {
                if(i != index && str.equals(word.substring(i, i + 1)))
                    return "+";
            }
        }
        return "*";
}
    
public String getHint(String str)
{
        String hint = "";
        for(int i = 0; i < word.length; i++)
        {
            hint += inWord(str.substring(i, i + 1), i);
        }
        return hint;
}

in both for loops this error keeps appearing and I am not quite sure what approach I can apply to fix this


Solution

  • You are trying to get the String length by using word.length, which is asking the JVM the property named "length" of the String, which is not public. You want to call word.length() which is a method and does exactly what you need.

    Also, I reccomend using a proper debugger.