Steve Dav
Steve Dav

Reputation: 43

Error in Returning in a Method

I have a very simple question about the following toString() method that I have created below. If words is an arrayList with the contents of {apple, banana, grape}, I was just wonderning if the method:

public String toString()
{
    for (int d = 0; d < words.size(); d++)
    {
        return "The word: " + words.get(d);
    }
    return "";
}

would return:

The word: apple
The word: banana
The word: grape

The reason that I ask this question is because when I ommited the line:

return "";

I got an error that said missing return statement, so I figured the computer might not be recognizing the return statement:

"return "The word: " + words.get(d);"

and instead of returning:

The word: apple
The word: banana
The word: grape

It would return:

null or ""

I am not sure if this is necessary, but I have also just put in the code that I had before I got the error missing return statement.

public String toString()
{
    for (int d = 0; d < words.size(); d++)
    {
        return "The word: " + words.get(d);
    }
}

The exact error was a red line that circled the second to last closed bracket. The exact error message was: "missing a return statement"

Update 1:

I really appreciate all the help and constructive criticism of the code that I can get. I hope I didn't turn this simple question into one too complex. Thank you very much :)

Update 2:

I am sorry for leaving so many notes. However, I was only just wondering if this is a common question that any of you guys see a lot because it seems like this comes up a lot in class, and the teacher assisstant can't answer the question. Thanks again :)

Upvotes: 0

Views: 42

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201399

You can only return one String from your method, not the individual String(s) you are currently trying to construct. Instead, use something like a StringBuilder to build your entire output and return once.

public String toString() {
    StringBuilder sb = new StringBuilder();
    for (int d = 0; d < words.size(); d++) {
        sb.append("The word: ").append(words.get(d)) //
                .append(System.lineSeparator());
    }
    return sb.toString();
}

Or the less efficient (but still StringBuilder, just many temporary and invisible ones)

public String toString() {
    String sb = "";
    for (int d = 0; d < words.size(); d++) {
        sb += "The word: " + words.get(d) + System.lineSeparator();
    }
    return sb;
}

Upvotes: 1

Related Questions