Java 程式生成乘法表


在本文中,我們將瞭解如何列印乘法表。使用 for 迴圈迭代 10 次所需輸入以建立乘法表,並在每次迭代中將輸入值與 1 到 10 的數字相乘。

下面演示了相同的概念 −

輸入

假設我們的輸入為 −

Input : 16

輸出

理想輸出為 −

The multiplication table of 16 is :
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
16 * 8 = 128
16 * 9 = 144
16 * 10 = 160

演算法

Step 1 – START
Step 2 – Declare two integer values namely my_input and i.
Step 3 - Read the required values from the user/ define the values
Step 4 – Iterate from 1 to 10 using a for-loop, and in each iteration, multiply the numbers 1 to
10 with the input.
Step 5- Display the resulting value in after each iteration.
Step 6- Stop

示例 1

在這裡,使用者根據提示輸入輸入。您可以在程式碼練習工具中親身體驗此示例 run button

import java.util.Scanner;
public class MultiplicationTable {
   public static void main(String[] args) {
      int my_input, i;
      my_input = 16;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter a number : ");
      my_input = my_scanner.nextInt();
      System.out.println("The multiplication table of " +my_input + " is :");
      for(i = 1; i <= 10; ++i){
         System.out.printf("%d * %d = %d \n", my_input, i, my_input * i);
      }
   }
}

輸出

Required packages have been imported
A reader object has been defined
Enter a number : 16
The multiplication table of 16 is :
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
16 * 8 = 128
16 * 9 = 144
16 * 10 = 160

示例 2

在這裡,整數已經預先定義,並在控制檯上訪問和顯示其值。

public class MultiplicationTable {
   public static void main(String[] args) {
      int my_input, i;
      my_input = 16;
      System.out.println("The number is defined as " +my_input);
      System.out.println("The multiplication table of " +my_input + " is :");
      for(i = 1; i <= 10; ++i){
         System.out.printf("%d * %d = %d \n", my_input, i, my_input * i);
      }
   }
}

輸出

The number is defined as 16
The multiplication table of 16 is :
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
16 * 8 = 128
16 * 9 = 144
16 * 10 = 160

更新於:2022-2-21

876 次瀏覽

開啟您的 職業生涯

透過完成課程,獲得認證資格

立即開始
廣告
© . All rights reserved.