Spaces:
Running
Running
File size: 1,605 Bytes
8e13e28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | 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
***
***
***
|