源碼清單:
/** *//**
* SupperRhombus.java
* Java控制台超級菱形列印方法
* @author 鄧超(CodingMouse)
* @version 0.1 2008-5-6
* 開發/測試環境:jdk1.6 + eclipse SDK 3.3.2
*/
//匯入Scanner類和PrintStream類
import java.util.Scanner;
import java.io.PrintStream;
public class SupperRhombus ...{
public static void main(String[] args) ...{
Scanner input = new Scanner(System.in);
//迴圈標識
boolean con = true;
//菱形的行數
int line;
do ...{
con = false;
System.out.print("請輸入要列印的菱形層數[不小於3的奇(整)數]:");
//獲得控制台使用者輸入的菱形行數
line = input.nextInt();
if (line % 2 == 0 || line < 3) ...{
System.out.println("只能輸入不小於3的奇(整)數!請重試!");
con = true;
}
} while (con);
//控制台輸出提示
System.out.println(line + "層菱形圖案如下: ");
//因為菱形的行數不能是偶數,要轉為奇數
line = (line & 1) == 0 ? line + 1 : line;
PrintStream out = System.out;
for (int i = 0 - line / 2 ; i <= line / 2 ; i++) ...{
for (int j = 0 - line / 2 ; j <= line / 2 ; j++) ...{
//把 == 改成 <= 或 >= ,還可產生其產的圖形
//out.print(((Math.abs(i) + Math.abs(j)) == line / 2) ? "* " : " "); //空心菱形
//out.print(((Math.abs(i) + Math.abs(j)) <= line / 2) ? "* " : " "); //實心菱形
out.print(((Math.abs(i) + Math.abs(j)) >= line / 2) ? "* " : " "); //內嵌菱形
}
out.println();
}
}
}
執行效果:
請輸入要列印的菱形層數[不小於3的奇(整)數]:11
11層菱形圖案如下:
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *