1. 程式人生 > >JAVA輸出“*”多層金字塔

JAVA輸出“*”多層金字塔

JAVA輸出多層金字塔

以下是程式原始碼:

import java.util.Scanner;
public class Test07{						//“Test07”需與檔名相同
	public static void main(String []args){
		Scanner sc = new Scanner(System.in);		//鍵盤控制器
		System.out.println("請輸入金字塔層數:");
		int a = sc.nextInt();				//將輸入的數值賦給變數“a”
		
		for(int i=1;i<=a;i++){				//迴圈輸出,有幾行
for(int n=1;n<=a-i;n++){ //根據有幾行來確定輸出幾個空格 System.out.print(" "); //輸出填充的空格 } for(int j=1;j<=(2*i-1);j++){ //迴圈輸出,每行有幾個“*” System.out.print("*"); } System.out.println(); } } }

以下是程式執行結果:

此處為了效果明顯輸入了四十層,大家可以嘗試九百九十九層