[英]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.