2006年12月3日 星期日

Java 程式流程

使用 switch 敘述
//獎金判斷程式
public class grade {
public static void main(String[] args) {
char grade = PPJUtil.getChar("成績");
int bonus = 0;
switch (grade) {
case 'A':
//成績為 A的時候,設定獎金為 50000
bonus = 50000;
break;
case 'B':
//成績為 B的時候,設定獎金為 30000
bonus = 30000;
break;
case 'C':
//成績為 C的時候,設定獎金為 10000
bonus = 10000;
break;
default:
//其他成績設定獎金為 1000
bonus = 1000;
}
System.out.println("Grade:"+grade);
System.out.println("Bonus:"+bonus);
}
}
switch 結構適用於檢測相等的情況。如果要用條件判斷的話,要使用 if 和 if/else 的敘述。
[!] switch 只能接受 int、short、byte、char 這4種變數型態。

迴圈 while 與 do / while
//輸出 1-5
int count = 1;
//布林值為真時候,會持續執行
while ( count <= 5 ) {
System.out.println(count);
count++;
//要記得讓 count 變數增加,否則將無法離開迴圈
}
迴圈是一個很方便的工具,可以重複同樣的工作。
int max = PPJUtil.getInt("輸入每列星星數量");
int maxline = PPJUtil.getInt("輸入行數");
int count = 1;
int line = 1;

//外迴圈 (當行數小於最大行數的時候,繼續執行)
while (line <= maxline) { //內迴圈 (當星星數未達每行星星數的時候,繼續執行)
count = 1;
while ( count <= max ) { System.out.print("*");
count++;
}
//內迴圈結束
System.out.print("\n");
line++;
}
//外迴圈結束
除此之外,也可以先要求執行某件事情,然後把判斷式放在後面,用 do 配合 while
//外迴圈
do {
count = 1;
//內迴圈:持續印出 "*",直到到達每行所需星星數
do {
System.out.print("*");
count++;
} while (count <= max); System.out.print("\n");
//內迴圈結束
line++;
} while (line <= maxline); //外迴圈結束
for 的迴圈
int max = PPJUtil.getInt("輸入每列星星數量");
int maxline = PPJUtil.getInt("輸入行數");
for (int line=1; line <= maxline; line++) {
for (int count=1; count<=max; count++) {
System.out.print("*");
}
System.out.print("\n");
}
練習
int max = PPJUtil.getInt("輸入累進數");
int total = 0;
for (int count=1; count<=max; count++) {
if (countSystem.out.print(count+"+");
}
else if (count==max) {
System.out.print(count+"=");
}
total += count;
}
System.out.println(total);

沒有留言: