Java学习:打印金字塔和九九乘法表

时间:2021-11-20 08:23:54

在打印金字塔之前,练习打印如图图形:

Java学习:打印金字塔和九九乘法表

采用双重循环,分别控制行数和每行打印星星的个数。

java代码:

package com.lissdy;

public class tuxing1 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int i = 5;
		for (int j = 1; j <= i; j++) {
			int times = j;
			while (times != 0) {
				System.out.print("*");
				times--;
			}
			System.out.print("\n");
		}
	}
}

在此基础上,对代码进行改进,打印出金字塔形图案

Java学习:打印金字塔和九九乘法表

分析图形,得出空格和*号的关系:

每行的空格数为:总行数-该行行数

每行*号数位:(该行行数*2)-1

java代码:

package com.lissdy;

public class tuxing2 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int i = 5;
		for (int j = 1; j <= i; j++) {
			//控制星号数量
			int times = (2*j)-1;
			//控制空格数量
			int time=0;
			//根据规律,做出限定
			while(time!=(i-j))
			{
				System.out.print(" ");
				time++;
			}
			while (times != 0) {
				System.out.print("*");
				times--;
			}
			System.out.print("\n");
		}
	}
}

打印九九乘法表:

public class mult {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= i; j++) {//列对其,否则会有些错位
				if ((i == 3 && j == 3) || (i == 4 && j == 3)) {
					System.out.print(" " + i + "*" + j + "=" + i * j + "  ");
				} else
					System.out.print(i + "*" + j + "=" + i * j + "  ");
			}
			System.out.print("\n");
		}

	}

}

打印结果:

Java学习:打印金字塔和九九乘法表