Skip to content

Instantly share code, notes, and snippets.

@faryne
Created May 17, 2012 14:05
Show Gist options
  • Save faryne/2719136 to your computer and use it in GitHub Desktop.
Save faryne/2719136 to your computer and use it in GitHub Desktop.
根據使用者輸入的數字,產生一個以星號組成的塔狀圖形
import java.util.Scanner;
class test {
/**
* @param args
*/
public static void main(String[] args) throws java.lang.Exception {
// TODO Auto-generated method stub
try {
System.out.print("Enter a number: "); // 準備讓使用者輸入數字
Scanner scanner = new Scanner(System.in); // 取得使用者的輸入
String target = scanner.next();
int a = Integer.parseInt(target); // 將使用者的輸入轉換成integer
if (a % 2 == 0) { // 當發現使用者的輸入為偶數時拋出例外
throw new Exception("Must be an odds");
}
up(a); // 負責產生結果的兩個functions
bottom(a);
} catch (Exception e) {
System.out.println("error:");
System.out.println(e.getMessage());
}
}
public static void up (int a) {
int i = 1;
for (; i < a; i += 2) {
int j = (a - i) / 2;
for (int k = 0; k < a; k++) {
if (k < j || k > (i + j - 1)) System.out.print(" ");
else System.out.print("*");
}
System.out.println("");
}
}
public static void bottom (int a) {
for (int i = a; i >= 1; i -= 2) {
int j = (a - i) / 2;
for (int k = 0; k < a; k++) {
if (k < j || k > (i + j - 1)) System.out.print(" ");
else System.out.print("*");
}
System.out.println("");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment