【最新 Java 8 程式語言 第四版 -練習題&解答】第六章 流程控制(二):迴圈
1.試寫一程式,可計算出1-100間所有3的倍數之總和
import java.io.*;
public class first6a1{
public static void main(String args[]) throws IOException {
// 宣告累加值 sum 及計算範圍 range
int sum = 0, range=100;
System.out.print("1-100間所有3倍數總和:");
int i=0; // 宣告迴圈變數 i
while (i<=range) { // 當 i 值大於 range 即停止執行的 while 迴圈
sum += i; // 每次進入迴圈時, 將 sum 的值加上 i
i+=3; // 每次都將 i 值加 2
}
System.out.println("1 到 100"+" 的所有3倍數總和為 "+sum);
}
}
7.試寫一程式,可以繪製出如下的菱形
*
***
*****
*******
*****
***
*
public class first6a7{
public static void main (String [] argv){
System.out.println(" * ");
System.out.println(" *** ");
System.out.println(" ***** ");
System.out.println(" ******* ");
System.out.println(" ***** ");
System.out.println(" *** ");
System.out.println(" * ");
}
}

關於第7題的解答應當如下(理由:此章節為迴圈,應用迴圈繪製) public static void main (String[] args) { //上半部 for(int Q=1;Q<=4;Q++){ for(int W=3;W>=Q;W--){ //" "此為空格 System.out.print(" "); } //2*Q-1 = 2*1-1=「1」、2*2-1=「3」、2*3-1=「5」...... for(int E=1;E<=2*Q-1;E++ ){ System.out.print("*"); } System.out.println(); } //下半部 for(int Q=1;Q<=3;Q++){ for(int W=1;W<=Q;W++){ System.out.print(" "); } for(int E=5;E>=2*Q-1;E-- ){ System.out.print("*"); } System.out.println(); } }
謝謝您的指教!