我必須完成一個問題。在循環內使用變量和Java中的if語句
現在的問題是:寫一個程序,每天的日照時間(每天的陽光輸入)爲給定的天數(輸入天數)。輸出日照時數最多的日子和日照時數最少的日子。
我已經完成了使用列表這個問題,但我的老師說,她要我用一個nested loop
或一個loop
和if
聲明。
到目前爲止,我輸入天數並運行while loop
向用戶詢問每天的日照時數。問題在於比較每個循環迭代的輸入(找出一天中最高和最低的陽光總量)。
CODE:
import java.util.Scanner;
public class temp {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of days you wish to enter the daylight hours for: ");
int loop_num = new_scan.nextInt();
for(int x=0; x<=loop_num;x++){
//Here I ask the user to input the number of sunlight hours for each day, I don't know how to compare separate input iterations (to find the highest and lowest days of sunlight).
System.out.println("Enter the number of daylight hrs for day "+ x);
int next_num = new_scan.nextInt();
int c = 0;
int old_num = c + next_num;
if(next_num>old_num){
int highest_num = next_num;
} else{ int highest_num = old_num; }
if(next_num<old_num){
int lowest_num = next_num;
} else{ int lowest_num = old_num; }
}
System.out.println("The lowest amount of sunlight of the days given was: "+ lowest_num);
System.out.println("The highest amount of sunlight of the days given was: "+ highest_num);
}
}
我的問題是:我如何比較迭代找到與陽光的最高和最低量天的日照量? 換句話說,如何比較循環中不同迭代的輸入數據?
'int min = 0',應該用不同的值初始化(可能是'Integer.MAX_VALUE')。 – Zereges
作爲最小值,你應該使用無窮大而不是0。但最好的辦法是使用第一次加值(與最小值相同)。 – dey
謝謝。如果那裏幾乎沒有負數的小時數(或24小時內的數字)-1就足夠了。無論如何,這應該是輸入健全性檢查的一部分,而不是進一步計算。 –