第六章:迴圈結構(二)
第一題:
package cn.bdqn.demo;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
int sum = 0; //學習總時間
double avg = 0; //平均時間
for (int i = 0; i < 5; i++) {
Scanner input=new Scanner(System.in);
System.out.print("請輸入周"+(i+1)+"的學習時間:");
int time = input.nextInt();
sum = sum+time;
avg = (double)sum/5;
}
System.out.println("週一至週五每日平均學習時間是:"+avg+"小時");
}
}
第二題:
package cn.bdqn.demo;
public class Exercise {
public static void main(String[] args) {
int chookNum = 0; // 雞的數量
int rabbitNum = 0; // 兔子的數量
for (; chookNum >= 0 && chookNum <= 35; chookNum++) {
rabbitNum = 35 - chookNum; //兔子的數量
int sum = chookNum + rabbitNum; //總數
int footsum = 2 * chookNum + 4 * rabbitNum; //腿的數量
if (sum == 35 && footsum == 94) {
System.out.println("雞有:"+chookNum+"只"+"\n"+"兔有:"+rabbitNum+"只");
}
}
}
}
第三題:
package cn.bdqn.demo;
public class Exercise1 {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) { // 1~100;
if (i % 3 == 0 && i % 5 == 0) { // 又是3的倍數又是5的倍數;
System.out.println("Flip2");
}
if (i % 3 == 0) { // 3的倍數;
System.out.println("Flip");
continue;
}
if (i % 5 == 0) { // 5的倍數;
System.out.println("Flop");
continue;
}
if (!(i % 3 == 0 && i % 5 == 0)) {
System.out.println(i);
}
}
}
}
第四題:
package cn.bdqn.demo;
public class Exercise2 {
public static void main(String[] args) {
int men,women,kids;
for (kids = 1; kids<=50; kids++) {
for(women = 1; women <=25; women++) {
for (men = 1 ; men <=16 ; men++) {
if(men*3+women*2+kids==50) {
if(men+women+kids==30) {
System.out.println("男人有:"+men+"\t"+"女人有:"+women+"\t"+"小孩有:"+kids);
}
}
}
}
}
}
}