KaiquanMah's picture
Create 14b Starsquare
8e13e28 verified
raw
history blame
1.61 kB
Write the method
StringBuilder square(int sideLength)
which returns a square of asterisks in one StringBuilder string.
You can make a line break inside a string with the character "\n", e.g.
System.out.println("aaa\nbbb");
prints:
aaa
bbb
Example method call:
public static void main(String[] args){
System.out.println(square(3));
System.out.println();
StringBuilder largerSquare = square(6);
System.out.println(largerSquare);
}
Program outputs:
***
***
***
******
******
******
******
******
******
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
int[] p = {2,4,6,3};
for (int pa : p) {
System.out.println("Testing with parameter " + pa);
StringBuilder square = square(pa);
if (square.charAt(square.length() -1) == '\n') {
square.deleteCharAt(square.length() -1);
}
System.out.println(square);
System.out.println("");
}
}
public static StringBuilder square(int sideLength) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sideLength; i++) {
for (int j = 0; j < sideLength; j++) {
sb.append("*");
}
sb.append("\n");
}
return sb;
}
}
Testing with parameter 2
**
**
Testing with parameter 4
****
****
****
****
Testing with parameter 6
******
******
******
******
******
******
Testing with parameter 3
***
***
***