缺少带有for循环的return语句 [英] Missing return statement with for loop

查看:100
本文介绍了缺少带有for循环的return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维布尔数组'poorSignal',需要编写一个返回网格的方法,如果数组上的某个点为true,则显示X,如果为false,则显示O.这是我的代码:

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";
    }
}

当我编译时,它在方法的最后一行给了我丢失的返回语句".我也不确定在打印数组时'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.

推荐答案

编译器无法知道该循环是否真正运行,因此,您还必须在外部循环之外具有return语句.

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

但是,如果我看一下您的代码,则不确定返回是否是您真正想要的.如果要打印整个矩阵,则可能要使用StringBuilder,然后在循环内使用append方法.在外部循环之后,使用toString方法返回构建器的字符串表示形式,如下所示:

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();
// loop
sb.append(someValue); 
sb.append('\n');
// after loop
return sb.toString();

这篇关于缺少带有for循环的return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆