将零加一个数字,可以吗?

public class MultiplicationTable {

public static void main (String[]a){

int[] x;

x = new int[10];

int i;

int n=0;

for (i=0;i<x.length;i++){

n++;

x[i]=n;

System.out.print(x[i] + " ");

}

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[0] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[1] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[2] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[3] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[4] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[5] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[6] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[7] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[8] * x[i] + " ");

System.out.println();

for (i=0;i<x.length;i++)

System.out.print(x[9] * x[i] + " ");

}

}

这是一个程序,它将显示一个乘法表,如下所示:

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

================================================== =============

它正在运行并且正确,但是我希望它看起来像这样:

01 02 03 04 05 06 07 08 09 10

01 02 03 04 05 06 07 08 09 10

02 04 06 08 10 12 14 16 18 20

03 06 09 12 15 18 18 24 24 30

04 08 12 16 20 24 28 32 36 40

05 10 15 20 25 30 35 40 45 50

06 12 18 24 30 36 42 48 54 60

07 14 21 28 35 42 49 56 63 70

08 16 24 32 40 48 56 64 72 80

09 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

==============================================

有什么办法吗?

回答:

是的你可以!您可以String.format用来在输出中添加零填充。

例:

String.format("%05d", 2)会产生00002

当前代码的一些改进:

我不确定您为什么打算将数字存储在数组中(也许出于练习目的),但这不是必需的,因为无论如何它会从1变为10。尽管如果您想这样做,则不需要in

for (i=0; i<x.length; i++){

x[i] = i+1;

System.out.print(x[i] + " ");

}

其次,我确定您意识到您有很多重复的代码,而且它们是连续的。您可以使用2个嵌套的for循环来做到这一点,而不用使用10个单循环:

for (int row = 1; row <= 10; row++) {

for (int col = 1; col <= 10; col++)

System.out.print(String.format("%03d", row * col));

System.out.println();

}

以上是 将零加一个数字,可以吗? 的全部内容, 来源链接: utcz.com/qa/409749.html

回到顶部