Home > DeveloperSection > Forums > Missing return statement in loop
Elena Glibart
Elena Glibart

Total Post:33

Points:233
Posted on    November-05-2014 3:20 AM

 Java Array  For Loop  Loop 
Ratings:


 1 Reply(s)
 640  View(s)
Rate this:

I have a two-dimensional boolean array 'poorSignal' and need to write a method that returns a grid, where if a point on the array is true an X is displayed, if false a O is displayed. Here is my code:

    public String display()
{
    for(int i = 0; i < mapSize; i++)
    {
        for(int j = 0; j < mapSize; j++)
        {
            if(poorSignal[i][j] = true)
            {
                return "O ";
            }
            else
            {
                return "X ";
            }
        }
        return "\n";
    }
}

When I compile, it gives me 'missing return statement' on the very last line of the method. I am also unsure if the 'return "\n" will work to add a new line when printing the array.

It's a question for an assignment, so I can't print it directly or just print the boolean values - it must be a method that produces the grid.



Hugh Jackman
Hugh Jackman

Total Post:52

Points:366
Posted on    November-05-2014 5:16 AM

The compiler cannot know whether the loop is actually run, therefore you must also have a return statement outside the outer loop.

But then, if I look at your code, I am not sure whether returning is what you really want there. If it is your intention to print the entire matrix, you might want to use a StringBuilder and then use the append method inside the loops. After the outer loop, return a string representation of the builder using the toString method like so:

StringBuilder sb = new StringBuilder();
sb.append(someValue); 
sb.append('\n');
return sb.toString();

Don't want to miss updates? Please click the below button!

Follow MindStick