使用循环然后If和Else

时间:2014-04-23 02:46:21

标签: java

我有一个ToString()方法,我需要运行但需要使用循环而不是if和else语句。我该怎么办?

public String toString() 
    {

        if (collectedDots == 0)
            return "Player[]"+"("+x+","+Math.abs(y)+")";
        else if (collectedDots == 1)
            return "Player["+"*"+"]"+"("+x+","+Math.abs(y)+")";
        else if (collectedDots == 2)
            return "Player["+"**"+"]"+"("+x+","+Math.abs(y)+")";
        else 
            return "Player["+"***"+"]"+"("+x+","+Math.abs(y)+")";

    }

3 个答案:

答案 0 :(得分:0)

您可以使用switch代替if

switch(collectedDots )
{
case 0:        return "Player[]"+"("+x+","+Math.abs(y)+")";
case 1:        return "Player["+"*"+"]"+"("+x+","+Math.abs(y)+")";
case 2:        return "Player["+"**"+"]"+"("+x+","+Math.abs(y)+")";
default:         return "Player["+"***"+"]"+"("+x+","+Math.abs(y)+")";
}

答案 1 :(得分:0)

编写一个产生collectedDots星号字符串的循环:

String asterisks = "";
// Here is your loop. It iterates "collectedDots" times
for (int i = 0 ; i != collectedDots ; i++) {
    // Append an asterisk to the string "asterisks"; I assume that you know how to do that
}

手持asterisks字符串后,toString的其余部分变得微不足道:

return "Player["+asterisks+"]"+"("+x+","+Math.abs(y)+")";

答案 2 :(得分:0)

花更多时间看看你的外线。

您的老师是否教过如何在课堂上打印以下模式?

(无)

A

AA

AAA

public static void main(String[] args) {
    StringBuilder stringBuilder = new StringBuilder();
    for(int i = 0; i < 4; i++) {
        System.out.println(stringBuilder.toString());
        stringBuilder.append("*");
    }
}