我的任務]( https://i.stack.imgur.com/dmCPJ.png )
我對此很陌生,如果我不清楚,很抱歉。到目前為止,我的代碼作業了一年(12 個月),但是當我想找到兩年(24 個月)的平均降雨量時,它找到了 48 個月。
不知道如何解決這個問題,或者問題出在哪里
import java.util.Scanner;
public class AverageRainfall {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("How many years did it rain? ");
int years = kb.nextInt();
for (int i = 1; i <= years; i ){
for(int j = 1; j <= (years * 12); j ){
System.out.println("How many inches of rain this month?");
totalRain = kb.nextInt();
System.out.println("Month: " j);
System.out.println(totalRain " Inches of rain!" );
}
}
System.out.println("The average rainfall over the period of: " years "years is:" totalRain/(12*years) "Inches");
}
}
我嘗試在我的 for 回圈條件中更改內容,但我無法弄清楚
uj5u.com熱心網友回復:
您的代碼中的主要問題是您每年回圈超過 12 * 年(如果您有 2 年,您將在 24 個月內回圈兩次)。您應該只使用內部回圈來回圈每個月,或者只使用一個 12 * 年的回圈
另請注意,使用 .close() 方法關閉 Scanner 是一種很好的做法。
如果您是新手,我建議您始終為變數使用有意義的名稱,例如,您可以將“kb”重命名為“scanner”,因為當代碼較長時,讀者會失去“kb”的背景關系,在無論如何,您都不應該縮短單詞,至少使用“鍵盤”代替
在將字串與變數連接時,您還需要添加一些空格,否則您會看到“9 年期間”之類的內容
這是你的代碼,我利用了作業中所述的結構,并添加了一些資訊來改善用戶體驗和他隨時輸入的資訊
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many years did it rain? ");
int years = scanner.nextInt();
int totalRain = 0;
for (int i = 1; i <= years; i ){
System.out.println("Lets go with year " i ":");
for(int j = 1; j <= 12; j ){
System.out.println("How many inches of rain in month " j " ?");
totalRain = scanner.nextInt();
System.out.println(totalRain " inches of rain in total!" );
}
}
System.out.println("The average rainfall over the period of: " years " years is: " totalRain/(12*years) " inches.");
scanner.close();
}
uj5u.com熱心網友回復:
嘗試在要中斷的條件下使用 break 陳述句。在這種情況下,您可以輕松擺脫困境。您已經每年回圈,因此您不需要在下一個回圈中再次乘以年份。原文:for(int j = 1; j <= (years * 12); j )更改:for(int j = 1; j <= 12; j )
這是一些參考:https ://www.programiz.com/java-programming/break-statement
import java.util.Scanner;
public class AverageRainfall {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("How many years did it rain? ");
int years = kb.nextInt();
int totalRain = 0;
for (int i = 1; i <= years; i ){
for(int j = 1; j <= 12; j ){
System.out.println("How many inches of rain this month?");
totalRain = kb.nextInt();
System.out.println("Month: " j);
System.out.println(totalRain " Inches of rain!" );
}
}
System.out.println("The average rainfall over the period of: " years "years is:" totalRain/(12*years) "Inches");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/522540.html
標籤:爪哇循环for循环
