簡體   English   中英

Java中的乘法表使用方法

[英]Multiplication table in Java using a method

編寫一個方法,該方法根據兩個輸入值返回乘法表,這些值指定要相乘的兩個數字范圍。 例如,如果該方法被指定為 3 和 4 作為輸入,它將返回一個字符串,該字符串在打印時將如下所示:

1 2 3 4

2 4 6 8

3 6 9 12

輸出要求:

每個數字后必須跟一個制表符。 每行后面必須跟一個換行符(包括最后一行)。 列和行的范圍應從 1 到輸入數字。 方法簽名應如下所示:

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

完成此方法后,從 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);
     }

這是我的輸出:

測試乘法表期望:

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

實際的:

12 輸出相等? 錯誤的

我覺得我有正確的設置,但我不知道如何獲得預期的輸出。

您的multiplicationTable方法正在打印,並且不太合法。 構建表並將其返回。 就像是,

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();
}

沒有其他變化,然后我得到

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