2

方法:

public String getRowsOf3Stars (int rows)

描述:

必修练习 2) 完成 getRowsOf3Stars 方法,该方法传递一个 int(rows) 作为参数。该方法返回一个包含该数量的 3 星行的字符串。

例如,

getRowsOf3Stars(2)  // returns “***\n***\n”

如果 rows 小于 1,则返回一个空字符串。一个例子:

getRowsOf3Stars(2)  // should return "***\n***\n"

我写的:

public String getRowsOf3Stars (int rows) {
    String getRowsOf3Stars="***\n";
    if (rows<1){
        String none="";
        return none;
    }
    else{
        for(int starRows=1;starRows<rows;starRows++){
            return getRowsOf3Stars;
        }
    }
}

我在 CodeWrite 上收到的错误:

private String getRowsOf3Stars(int rows) throws Exception {
    >> This method must return a result of type String

有人可以解释为什么我的程序没有返回字符串吗?

4

4 回答 4

1

Java compiler would make sure that there is a string return from the method. Now see the code,

1) if(rows<1)

then only if will work and return a string.

2)But if (rows>=1)

then it will go to the for loop, and the compiler cannot determine at the compile time that the for loop will execute or not, as this is a runtime mechanism.So its not sure for the compiler that for loop will execute or not. And if for loop doesn't execute, your method will not return anything.

Now since compiler has to make it sure, that there should be a string return, it is showing that error.

So what you can do is that, in the else clause after for loop you can return a default string as return ""; or as per your requirement.

于 2013-05-01T05:19:28.730 回答
1

改变这个

for(int starRows=1;starRows<rows;starRows++){

return getRowsOf3Stars(starRows); //  your code here don't return any thing here.
于 2013-05-01T04:27:47.860 回答
1

放在return "";方法的最后一行以消除错误。它在抱怨,因为由于您的条件,您返回的当前线路可能永远不会被调用。

例如,如果您提供参数 rows = 1,则返回将永远不会发生。

于 2013-05-01T04:28:59.750 回答
0

除了不返回字符串的问题之外,我看不到内部循环的原因,因为您在循环内发出返回。我认为这会完成你想要的:

public String getRowsOf3Stars (int rows) {
String ROWOF3STARS = "***\n";
String returnString = "";

if (rows > 0){

    for(int starRows=1;starRows<rows;starRows++){
        returnString += ROWOF3STARS;
    }
}
return returnString;
}

希望这可以帮助。

于 2013-07-09T16:54:45.837 回答