第八章:迴圈結構進階
第一題:編寫程式,列印如下圖案,要求該圖案的行數由使用者輸入。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("請輸入行數:");
int lineNumber = input.nextInt();
for (int i = 1; i <= lineNumber; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j+" ");
}
System.out.println("");
}
}
}
第二題:買雞問題
public class Test1 {
public static void main(String[] args) {for (int i = 0; i <20; i++) { //迴圈公雞的數量
for (int j = 0; j < 33; j++) { //迴圈母雞的數量
for (int j2 = 0; j2 < 300; j2++) { //迴圈小雞的數量
if (((5*i)+(3*j)+(j2/3))==100 && (i+j+j2)==100) {
System.out.println("公雞有:"+(i+1)+"\t"+"母雞有:"+(j+1)+"\t"+"小雞有:"+(j2+1));
}
}
}
}
}
}
第三題:有三個班級各四名學員參賽,從控制檯輸入每個班級參賽學員的成績,要求統計出三個班級所有參賽學員中成績大於85分的學員的平均分,如何程式設計實現?
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
int [][] arr = new int [3][4]; //定義二維陣列,分別接受3個班的每個班上的4位同學的成績
int count = 0; //平均分大於85的人數
double avg = 0.0;//平均分大於85的同學的平均分
int totalScore = 0; //平均分大於85分的同學的總成績
for (int i = 0; i < arr.length; i++) {
int sum = 0;//初始化成績和
double avg1 = 0.0;//初始化平均分
System.out.println("第"+(i+1)+"個班的"+"成績");
for (int j = 0; j < arr[i].length; j++) {
Scanner input = new Scanner(System.in);
System.out.print("請輸入第"+(j+1)+"位同學的成績為:");
if (input.hasNextInt() == true) {
int score = input.nextInt();
arr[i][j] = score;
sum += arr[i][j];
if (score>=85) {
count++;
totalScore += arr[i][j];
}
}
avg = totalScore/(count*1.0);
}
System.out.println("成績大於85分的學員的平均分的人數為:"+count);
System.out.println("成績大於85分的學員的平均分為:"+avg);
}
}
}
第四題:銀行取錢問題
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.print("請輸入密碼:");
int password =input.nextInt();
if (password == 123456) {
System.out.print("請輸入金額:");
int money = input.nextInt();
while ((money % 100 == 0 && money > 0 && money <= 1000) == false) { // 迴圈判斷使用者輸入的金額是否符合銀行的出錢條件
System.out.print("您輸入的金額不合法,請重新輸入:");
money =input.nextInt();
}
System.out.print("您取出了" + money + "元\n");
break;
} else {
if (i == 2) {
System.out.println("密碼錯誤,請取卡!");
}
continue;
}
}
System.out.println("交易完成,請取卡!");
}
}