-3

I have a ToString() method I need to run but need to use loops instead of if and else statements. 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)+")";

    }
devnull
  • 118,548
  • 33
  • 236
  • 227

3 Answers3

0

you can use switch instead of 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)+")";
}
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

Write a loop that produces a string of collectedDots asterisks:

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:

return "Player["+asterisks+"]"+"("+x+","+Math.abs(y)+")";
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Spent more time looking at your out put.

Did your teacher teach how to print the following pattern in class?

(nothing)

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("*");
    }
}
Mingtao Zhang
  • 148
  • 10