Java程序生成乘法表
在该程序中,您将学习生成给定数字的乘法表。这是通过在Java中使用for和while循环来完成的。
示例1:使用for循环生成乘法表
public class MultiplicationTable {
public static void main(String[] args) {
int num = 5;
for(int i = 1; i <= 10; ++i)
{
System.out.printf("%d * %d = %d \n", num, i, num * i);
}
}
}
运行该程序时,输出为:5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
也可以使用Java中的while循环来生成相同的乘法表。
示例2:使用while循环生成乘法表
public class MultiplicationTable {
public static void main(String[] args) {
int num = 9, i = 1;
while(i <= 10)
{
System.out.printf("%d * %d = %d \n", num, i, num * i);
i++;
}
}
}
运行该程序时,输出为:9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
在上面的程序中,与for循环不同,我们必须在循环体内增加i的值。
尽管两个程序在技术上都是正确的,但在这种情况下最好使用for循环。这是因为已知迭代次数(从1到10)。
本文介绍如何使用Java编程语言生成指定数字的乘法表。通过示例代码展示了使用for循环和while循环两种方法,并解释了两种循环之间的区别。
604

被折叠的 条评论
为什么被折叠?



