更新時間:2022-12-12 12:34:36 來源:動力節(jié)點(diǎn) 瀏覽1603次
在此程序中,您將學(xué)習(xí)生成給定數(shù)字的乘法表。這是通過在 Java 中使用 for 和 while 循環(huán)語句來完成的。
要理解此示例,您應(yīng)該具備以下Java 編程主題的知識:
Java for 循環(huán)
Java while 和 do...while 循環(huán)
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 循環(huán)生成。
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 循環(huán)不同,我們必須遞增在循環(huán)體內(nèi)。
雖然這兩個程序在技術(shù)上都是正確的,但在這種情況下最好使用 Java for 循環(huán)語句。這是因?yàn)榈螖?shù)(從 1 到 10)是已知的。
相關(guān)閱讀

初級 202925

初級 203221

初級 202629

初級 203743