user12392110
user12392110

Reputation:

Multiplication Table from ArrayList

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.

enter image description here

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

Answers (2)

WJS
WJS

Reputation: 40034

Here are a couple suggestions.

  1. Replace this :
    StringBuilder sb = new StringBuilder();
    sb.append(String.format("%4s", ""));

with this.

    StringBuilder sb = new StringBuilder("    "); // four spaces
  1. Even though you print out the table using System.out.println() it would look more like your desired image by appending a "\n" to the StringBuilder of each line.
    sb.append("\n");
  1. Finally, as a convenience, define the format specification as a string.
    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

Ralf Renz
Ralf Renz

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

Related Questions