Java 打印乘法表程序

编写一个 Java 程序,使用 For 循环、While 循环和函数(附带示例)来打印乘法表。在每种情况下,我们都必须使用嵌套循环,一个用于实际数字,另一个用于乘法目的(从 1 遍历到 10)。

Java 使用 For 循环打印乘法表程序

此程序允许用户输入任何整数值,并使用 For 循环打印从该数字到 9 的乘法表。

import java.util.Scanner;

public class MultiplicationTable {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int number, i, j;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number : ");
		number = sc.nextInt();	

		for(i = number; i < 10; i++)
		{
			for(j = 1; j <= 10; j++)
			{
				System.out.println(i +"  *  " + j + "  =  " + i * j);
			}
			System.out.println("================");
		}
	}
}
Program to Print Multiplication Table 1

在此示例中,第一个 For 循环用于从用户输入的数值迭代到 9。接下来,我们使用嵌套 For 循环将 j 从 1 迭代到 10。用户输入的数值 number = 9

第一个 For 循环 – 第一次迭代: for(i = 9; i < 10; i++)。此处,条件 i < 10 为 True。因此,它会进入第二个For 循环

第二个 For 循环 – 第一次迭代: for(j = 1; 1 <= 10; 1++)。条件为 True。因此,内部的Java system.out.println 语句会被打印。

第二个 For 循环 – 第二次迭代: for(j = 2; 2 <= 10; 2++)。条件为 True。因此,内部的语句会被打印。

第二个 For 循环会重复该过程,直到 j 达到 11。因为当 j 为 11 时,条件失败,所以会退出第二个循环。

第一个 For 循环 – 第二次迭代: for(i = 10; i < 10; i++)。条件 (10 < 10) 为 False。因此,会退出第一个 For 循环。

Java 使用 While 循环打印乘法表程序

此示例与上面相同,但我们使用的是While 循环。不要忘记 j++ 和 i++ 行;否则,您将陷入无限循环。

import java.util.Scanner;

public class Example1 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int i, j;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number : ");
		i = sc.nextInt();	

		while(i < 10)
		{
			j = 1;
			while(j <= 10)
			{
				System.out.println(i +"  *  " + j + "  =  " + i * j);
				j++;
			}
			System.out.println("================");
			i++;
		}
	}
}
 Please Enter any Number : 7
7  *  1  =  7
7  *  2  =  14
7  *  3  =  21
7  *  4  =  28
7  *  5  =  35
7  *  6  =  42
7  *  7  =  49
7  *  8  =  56
7  *  9  =  63
7  *  10  =  70
================
8  *  1  =  8
8  *  2  =  16
8  *  3  =  24
8  *  4  =  32
8  *  5  =  40
8  *  6  =  48
8  *  7  =  56
8  *  8  =  64
8  *  9  =  72
8  *  10  =  80
================
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
================

Java 使用函数打印乘法表程序

程序与第一个示例相同。但是,我们将乘法逻辑分开,并将其放在一个单独的方法中,以便您可以在各种位置使用它。

import java.util.Scanner;

public class MulTab2 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int number;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number : ");
		number = sc.nextInt();	

		printMulTab(number);
	}
	
	public static void printMulTab(int num)
	{
		int i, j;
		
		for(i = num; i < 10; i++)
		{
			for(j = 1; j <= 10; j++)
			{
				System.out.println(i +"  *  " + j + "  =  " + i * j);
			}
			System.out.println("================");
		}
	}
}
Program to print Multiplication Table using for loop and functions