乘法表弹出

时间:2016-09-28 02:32:34

标签: java multiplication

我搞乱了我的代码,但我还没有找到答案。 Format.left只是一个在每个数字之间放置空格的类。我试图将1到4的数字显示在一边,但它会一直弹出:

1      2      3      4      5      6
2      4      6      8     10     12
3      6      9     12     15     18
4      8     12     16     20     24

我希望我对你们有意义,我的英语非常糟糕。

for(cols = 1; cols <= 4; cols++)
    {
        for (rows = 1; rows <= 6; rows++)
        {
            System.out.print(Format.right(cols * rows,7));  
        }
        System.out.println();
    }

我正在寻找一些简短的样子:

    1   2   3   4   5
1   1   2   3   4   5
2   2   4   6   8   10
3   3   6   9   12  15
4   4   8   12  16  20
5   5   10  15  20  25

1 个答案:

答案 0 :(得分:0)

试试这个:

for(cols = 0; cols <= 4; cols++)
{
    for (rows = 0; rows <= 6; rows++)
    {
        if (rows == 0 || cols == 0) {
            System.out.print(Format.right(cols + rows, 7));
        }else {
            System.out.print(Format.right(cols * rows, 7));  
        }
    }
    System.out.println();
}

您希望每个行和列都移一个,所以我只是将循环设置为0而不是1,并添加了一个if语句来处理第一行/列的特殊情况。

相关问题