Reputation:
My task is to make and print a multidimensional array with the shape shown in the attachment.
To accomplish the task, I need to create a StringBuilder and Array list, then print each line in the main method using the for each loop.
Here's where I'm stuck and I don't really know how to move on.
public class MultiplicationTable {
public static void main(String[] args) {
for (String s : getMultiplicationTable(5)
) {
System.out.println(s);
}
}
public static List<String> getMultiplicationTable(int size) {
ArrayList<String> strings = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append(String.format("%4s", ""));
for (int i = 1; i <= size; i++) {
StringBuilder sb2 = new StringBuilder();
sb.append(String.format("%4d", i));
}
strings.add(sb.toString());
for (int i = 1; i <= size; i++) {
StringBuilder sb3 = new StringBuilder();
sb.append(String.format("%4d", i));
for (int j = 1; j <= size; j++) {
sb.append(String.format("%4d", i * j));
}
strings.add(sb.toString());
}
return strings;
}
}
Upvotes: 0
Views: 565
Reputation: 40034
Here are a couple suggestions.
StringBuilder sb = new StringBuilder();
sb.append(String.format("%4s", ""));
with this.
StringBuilder sb = new StringBuilder(" "); // four spaces
System.out.println()
it would look
more like your desired image by appending a "\n" to the StringBuilder of each line. sb.append("\n");
String format = "%4d";
Then in your print statements, use the format string instead of the actual format. That reduces the number of locations you have to edit if you want to change the spacing.
Upvotes: 0
Reputation: 1061
sb2 and sb3 are never used. And you never clear sb.
public class MultiplicationTable {
public static void main(String[] args) {
for (String s : getMultiplicationTable(5)) {
System.out.println(s);
}
}
public static List<String> getMultiplicationTable(int size) {
List<String> strings = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append(String.format("%4s", ""));
for (int i = 1; i <= size; i++) {
sb.append(String.format("%4d", i));
}
strings.add(sb.toString());
for (int i = 1; i <= size; i++) {
sb = new StringBuilder();
sb.append(String.format("%4d", i));
for (int j = 1; j <= size; j++) {
sb.append(String.format("%4d", i * j));
}
strings.add(sb.toString());
}
return strings;
}
}
Upvotes: 1