【发布时间】:2020-10-04 00:36:27
【问题描述】:
编写一个方法,该方法根据两个输入值返回一个乘法表,这两个输入值指定要相乘的两个数字范围。例如,如果方法被指定为 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 输出相等?假的
我觉得我的设置正确,但我不知道如何获得预期的输出。
【问题讨论】:
-
您没有在嵌套行、列循环的迭代之间保存字符串。也许 String a = ""; 在嵌套循环之前和 a += "" + num +"\t"; 在嵌套循环内。
-
.... 和
a += "\n";打印新行时应该没问题。