java练习7.16

package myapps;

import java.util.Scanner;

public class Practice {
	public static void main(String[] args) {
		Homework homework = new Homework();
		System.out.println("打印金字塔,请输入金字塔层数:");
		Scanner input = new Scanner(System.in);
		homework.printTower(input.nextInt());
		System.out.println("----------------------------------");
		System.out.println("打印乘法表,请输入数字:");
		homework.printTable(input.nextInt());
		System.out.println("----------------------------------");
		int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
		System.out.println("数组转置前:");
		printArray(arr);
		homework.transpose(arr);//数组转置
		System.out.println("数组转置后:");
		printArray(arr);
		input.close();
	}

	//打印二维数组
	private static void printArray(int[][] arr) {
		for (int i = 0; i < arr.length; i++) {
			System.out.print("{");
			for (int j = 0; j < arr[i].length; j++) {
				System.out.print(arr[i][j]);
				if (j != arr[i].length - 1) {
					System.out.print(",");
				}
			}
			System.out.print("}");
			if (i != arr.length - 1) {
				System.out.print(",");
			}
		}
		System.out.println();
	}
}

class Homework {
	/*
	 * 打印金字塔
	 */
	public void printTower(int layer) {
		for (int i = 0; i < layer; i++) {
			for (int j = 0; j < (2 * layer + 1); j++) {
				if ((j < layer - i - 1) || (j >= layer + i)) {
					System.out.print(" ");
				} else {
					System.out.print("*");
				}
			}
			System.out.println();
		}
	}

	/*
	 * 打印九九乘法表
	 */
	public void printTable(int num) {
		for (int i = 1; i <= num; i++) {
			for (int j = 1; j <= i; j++) {
				System.out.print(j + "×" + i + "=" + (i * j) + "\t");
			}
			System.out.println();
		}
	}

	/*
	 * 数组转置
	 */
	public void transpose(int[][] arr) {
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				if (j > i) {
					int temp = arr[i][j];
					arr[i][j] = arr[j][i];
					arr[j][i] = temp;
				}
			}
		}
	}
}

运行结果:


猜你喜欢

转载自blog.csdn.net/qq_36938011/article/details/81063368
今日推荐