Java 实现乘法口诀(99乘法表)

原创 HuangLongPu     发表于  2021-01-22 12:49       314

用 Java 程序实现乘法口诀(99乘法表),主要有两个要点需要掌握:

1、需要实现双层循环;

2、内循环的循环次数小于等于上层循环的循环次数;


Java 代码如下(供参考):

package com.test;

/**
 * Java 实现乘法口诀(99乘法表)
 */
public class MathMultiplyTable {

    public static void main(String[] args) {
        /**
         * 主要有两个要点:
         * 1、实现双层循环;
         * 2、内循环的循环次数小于等于上层循环的循环次数
         */
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                int result = i * j;
                System.out.print(j + " x " + i  + " = " + (result < 10 ? result + " " : result) + " ");
            }
            System.out.println();
        }
    }
}

循环内打印出口诀,采用条件表达式主要为判断乘积结果是否为两位数,如果不足两位,采用结果后加空格补齐,主要为打印结果的美化输出。

注意点:外循环每循环完一次,必须得进行一次换行输出,否则得不到99乘法表的效果图,代码 ”System.out.println()“ 仅为换行作用

结果如下:

1 x 1 = 1  
1 x 2 = 2  2 x 2 = 4  
1 x 3 = 3  2 x 3 = 6  3 x 3 = 9  
1 x 4 = 4  2 x 4 = 8  3 x 4 = 12 4 x 4 = 16 
1 x 5 = 5  2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25 
1 x 6 = 6  2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 36 
1 x 7 = 7  2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35 6 x 7 = 42 7 x 7 = 49 
1 x 8 = 8  2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40 6 x 8 = 48 7 x 8 = 56 8 x 8 = 64 
1 x 9 = 9  2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81 

Process finished with exit code 0