【发布时间】:2014-06-07 16:07:01
【问题描述】:
我有一个 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)+")";
}
【问题讨论】:
-
为什么要在这里使用循环。在这种情况下使用 Switch case 会是更好的选择
-
我该怎么做?这是关于打印特定数量的字符。考虑一下。毕竟,这是你的功课。
-
@ankhuri
switch并不理想,因为(1)它将collectedDots的数量限制为您的开关中的最高case,并且(2)它使您重复基本相同连接代码多次。 -
为了好玩,
for(;condition;){statment; break;}用作 if 语句,但从不需要 -
首先,使用
Math.abs(y)的临时值来消除混乱,让您更清楚地看到自己在做什么。
标签: java