Multiplication Table
This is my 2nd java code (actually, it's the 2nd code that I upload to my blog😝),and this is what I want to do after I learned java,to write a program for build a multiplication table.( from my own translation )
这是我的第二个代码(其实只是上传的第二个),也是我一直以来想做的一件事,编写一段程序输出乘法口诀表。
This is my second code (in fact, just the second uploaded), and one of the things I always wanted to do, write a program to output a multiplication table.( from https://translate.google.cn )
输出一个 9X9 乘法口诀表(java语言编写)
完整代码如下:
public class multable {
public static void main(String[] args) {
//生成乘数
for (int i = 1; i <= 9; i++) {
//生成被乘数
for (int j = 1; j <= 9; j++) {
if (i >= j) {
//对于3*3和3*4,输出的式子前多加一个空格,和下面的式子对齐
if ((i == 3 && j == 3) || (i == 4 && j == 3)) {
System.out.print(" " + j + "*" + i + "=" + (i * j) + " ");
} else {
//输出乘积式
System.out.print(j + "*" + i + "=" + (i * j) + " ");
}
} else {
//如果被乘数大于乘数,跳出循环
break;
}
}
//换行输出
System.out.println();
}
}
}
输出如下图:

编写心得
1.产生乘积式
先使用两个 for 循环产生被乘数 j 与乘数 i ,在内层循环通过
System.out.print(j + "*" + i + "=" + (i * j) + " ");
输出乘积式。
2.换行
内外层循环之间通过
System.out.println();
完成换行操作。
3.对齐
正常情况直接输出乘积式,对于 “3X3” 和 “3X4” 这两个式子,需要在输出的式子前面额外添加一个空格,使之与同一列的式子对齐,通过 if 语句实现 :
if ((i == 3 && j == 3) || (i == 4 && j == 3)) {
System.out.print(" " + j + "*" + i + "=" + (i * j) + " ");
}
其他情况直接输出即可。
4.跳出不必要的循环
当循环中被乘数 j 小于等于乘数 i 时,按顺序输出即可,当循环中被乘数 j 大于乘数 i 时,应跳出内层循环执行 i+1 ,通过 break 语句实现 :
if (i >= j) {
//此处为输出语句,省略
} else {
//如果被乘数大于乘数,跳出循环
break;
}
这样可以避免无效的循环,理论上应该可以减少一半的运行时间。
以上就是本人在编写这些代码时的一些思考和解决的问题。

浙公网安备 33010602011771号