简体   繁体   English

Java中的乘法表使用方法

[英]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:例如,如果该方法被指定为 3 和 4 作为输入,它将返回一个字符串,该字符串在打印时将如下所示:

1 2 3 4 1 2 3 4

2 4 6 8 2 4 6 8

3 6 9 12 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.列和行的范围应从 1 到输入数字。 The method signature should look as follows:方法签名应如下所示:

public static String multiplicationTable(int rows, int columns){} 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.完成此方法后,从 main 调用 testMT() 方法以确保它按预期工作。

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 1 2 3 4
2 4 6 8 2 4 6 8
3 6 9 12 3 6 9 12

Actual:实际的:

12 Outputs equal? 12 输出相等? 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.您的multiplicationTable方法正在打印,并且不太合法。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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