-------噠噠~~~~~~~~~~
html
從圖中,咱們能夠發現:第1行的空格爲4個,第2行是3個,第3行是2個,……,每行依次遞減,直至最後一行空格數爲0;而星號數目是第1行是1個,第2行是3,第3行是5,……,每行依次遞增2,直至最後一行星號數爲9。總結數據,咱們能夠獲得表1.1所示的規律。java
行數 | 空格數 | 星星數 | ||
1 | 4 | 5-1 | 1 | 1*2-1 |
2 | 3 | 5-2 | 3 | 2*2-1 |
3 | 2 | 5-3 | 5 | 3*2-1 |
4 | 1 | 5-4 | 7 | 4*2-1 |
5 | 0 | 5-5 | 9 | 5*2-1 |
規律 | 依次減1 | 5-行數 | 依次加2 | 行數*2-1 |
根據圖中咱們能夠發現這種規律,那麼接下來是否是就簡單了。編程
3,肯定空格數框架
因爲每行空格數有着「5–行數」的規律。因此在第i行的時候,空格數就爲5–i。因此咱們只要把5–i個空格打印出來便可。spa
行數 | 空格數 | 星星數 | ||
1 | 0 | 1-1 | 9 | 5*2-1 |
2 | 1 | 2-1 | 7 | 4*2-1 |
3 | 2 | 3-1 | 5 | 3*2-1 |
4 | 3 | 4-1 | 3 | 2*2-1 |
5 | 4 | 5-1 | 1 | 1*2-1 |
規律 | 依次遞增1 | 行數-1 | 依次遞減2 | 行數*2-1(反向) |
package com.javase.demo;線程
import java.util.Scanner;htm
/**
* 金字塔
* @author Mr.Zhang
*
*/
public class Pyramid {
static Scanner input = new Scanner(System.in);
/**
* *****打印金字塔*****
* 1,肯定金字塔行數
* 2,確認空格數
* 3,確認星星數
* @param args
*/
public static void main(String[] args) {
entrance();
}blog
/**
* 入口項
*/
public static void entrance() {
System.out.println("請選擇(0--正金字塔,1--倒金字塔,2--菱形金字塔)");
String select = input.nextLine();
if(isNumber(select)){
int selectInt = Integer.parseInt(select);
switch(selectInt){
case 0:
uprightPyramid();
break;
case 1:
fallPyramid();
break;
case 2:
System.out.println("該功能還沒有完善!");
break;
default:
System.out.println("請輸入正確的選項!");
entrance();
break;
}
}else if(!select.equals(0) || !select.equals(1) || !select.equals(2)){
nullSuccess();
}
}ip
/**
* 打印正金字塔
* @param input
*/
public static void uprightPyramid() {
System.out.println("請輸入行數:");
String row = input.nextLine();
if(isNumber(row)){
int rows = Integer.parseInt(row);
for(int i = 1;i <= rows;i++){ //循環輸入的行數,
for(int j = 1;j <= rows - i;j++){ //輸出循環每行的空格
System.out.print(" ");
}
for(int k = 1;k <= 2 * i - 1;k++){ // 輸出循環每行的★
System.out.print("★");
}
System.out.println();
}
System.out.println("打印完成,線程結束");
}else{
nullSuccess();
}
}
/**
* 打印倒金字塔
*/
public static void fallPyramid(){
System.out.println("請輸入行數:");
String row = input.nextLine();
if(isNumber(row)){
int rows = Integer.parseInt(row);
for(int i = rows;i >= 1;i--){
for(int j = 0;j < rows-i;j++){ //打印空格數
System.out.print(" ");
}
for(int k = 0;k < i * 2 - 1;k++){ //打印★數
System.out.print("★");
}
System.out.println();
}
System.out.println("打印完成,線程結束");
}else{
nullSuccess();
}
}
/**
* 判斷是否爲數字
* @param str
* @return
*/
public static boolean isNumber(String str){
boolean ok = false;
if(null != str && str.matches("^[0-9]+$")){
return true;
}
return ok;
}
/**
* 調用錯誤結果
*/
public static void nullSuccess(){
System.out.println("您輸入的不是數字,一遍浪去,不聽話的孩子!");
}
get
}