简体   繁体   中英

Multiplication table in Java using a method

Write a method that returns a multiplication table based on two input values that specify what two ranges of numbers to multiply together. For example, if the method were given 3 and 4 as input, it would return a string that when printed, would look like this:

1 2 3 4

2 4 6 8

3 6 9 12

Output Requirements:

Each number must be followed by a tab character. Each line must be followed by a new line character (including the last row). The columns and rows should range from 1 to the input number. The method signature should look as follows:

public static String multiplicationTable(int rows, int columns){}

Call the testMT() method from main after completing this method to ensure it is working as expected.

public static String multiplicationTable(int rows, int columns) {

        for(int i = 1; i <= rows; i++){
            for(int j = 1; j <= columns; j++) {
                int num = i * j;
                String a = "" + num +"\t";
            }
            System.out.println("");
        }
        return String.format("%s", a); 
    }
public static void testMT() {
     System.out.println("Testing Multiplication Table");

     String expected = "1\t2\t3\t4\t\n2\t4\t6\t8\t\n3\t6\t9\t12\t\n";
     System.out.print("Expecting:\n" + expected);

     String actual = multiplicationTable(3, 4);
     System.out.print("Actual:\n" + actual);

     boolean correct = expected.equals(actual);
     System.out.println("Outputs equal? " + correct);
     }

Here is my output:

Testing Multiplication Table Expecting:

1 2 3 4
2 4 6 8
3 6 9 12

Actual:

12 Outputs equal? false

I feel like I have the right setup but I can't figure out how to get the expected output.

Your multiplicationTable method is printing, and not quite legal. Build the table and return it. Something like,

public static String multiplicationTable(int rows, int columns) {
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= columns; j++) {
            int num = i * j;
            sb.append(num).append('\t');
        }
        sb.append('\n');
    }
    return sb.toString();
}

With no other changes, I then get

Testing Multiplication Table
Expecting:
1   2   3   4   
2   4   6   8   
3   6   9   12  
Actual:
1   2   3   4   
2   4   6   8   
3   6   9   12  
Outputs equal? true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM