[英]Using of Loops then If and Else
I have a ToString() method I need to run but need to use loops instead of if and else statements.我有一个需要运行的 ToString() 方法,但需要使用循环而不是 if 和 else 语句。 How should i do it?我该怎么做?
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)+")";
}
you can use switch instead of if
你可以使用 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)+")";
}
Write a loop that produces a string of collectedDots
asterisks:编写一个循环,生成一串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
}
With asterisks
string in hand, the rest of your toString
becomes trivial:有了asterisks
字符串,其余的toString
就变得微不足道了:
return "Player["+asterisks+"]"+"("+x+","+Math.abs(y)+")";
Spent more time looking at your out put.花更多时间查看您的输出。
Did your teacher teach how to print the following pattern in class?你的老师在课堂上教过如何打印以下图案吗?
(nothing) (没有)
A一种
AA机管局
AAA 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("*");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.