該程序需要用戶輸入10個溫度,計算平均值,然後打印出高於平均值的臨時溫度。爲什麼我的程序重複相同的結果?
出於某種原因,我沒有看到,我舉三個溫度(100,90,70的順序)的輸入我得到這樣的輸出:
100 is an above average temperature.
100 is an above average temperature.
90 is an above average temperature.
但是,當我給這個輸入(70,90,100順序),我得到
70 is not an above average temperature.
70 is an above average temperature.
90 is an above average temperature.
70 is an above average temperature.
90 is an above average temperature.
70 is not an above average temperature.
java.lang.ArrayIndexOutOfBoundsException: 2
at Lab9.main(Lab9.java:64)
有人可以幫我看看我不是嗎?
import java.util.Scanner;
public class Lab9
{
public static int[] temps, aboveAvgTemps;
public static int temp, totalTemp, avgTemp, currentTemp, oldTemp, numAboveAvg,
numOfEntries;
public static void main(String[] args)
{
System.out.println("Welcome to the above average temperature tester program.");
System.out.println("Please in an integer for the number of days you wish to measure.");
Scanner kb = new Scanner(System.in);
numOfEntries = kb.nextInt();
System.out.println("Please enter in " + numOfEntries + " temperatures.");
//initialize main array and variables
temps = new int[numOfEntries];
totalTemp = 0;
for(int i = 0; i < temps.length; i++)
{
System.out.println("Please enter in the temperature for day " + (i+1) + ":");
temp = kb.nextInt();
temps[i] = temp;
totalTemp += temp;
}
//final calculations
avgTemp = totalTemp/numOfEntries;
System.out.println("The average temperature is " + avgTemp);
//count up num of above avg temps
for(int i = 0; i < temps.length; i++)
{
if(temps[i] > avgTemp)
{
numAboveAvg++;
}
}
//initialize new array and variables for above avg temps
aboveAvgTemps = new int[numAboveAvg];
for(int i = 0; i < temps.length; i++)
{
if(temps[i] > avgTemp)
{
for(int j = 0; j <= i; j++)
{
aboveAvgTemps[j] = temps[j];
System.out.println(aboveAvgTemps[j] + " is an above average temperature.");
}
}
else
{
System.out.println(temps[i] + " is not an above average temperature.");
}
}
}
}
歡迎來到StackOverflow。你有沒有在調試器中逐行執行代碼,一次一行?這會幫助你更快速地找到問題,而不是在這裏問問題,這是你應該做的。請訪問[幫助]並閱讀[問]以瞭解如何有效地使用本網站。 –
你不應該通過'i'在你的循環內部循環'j'。 – matt
你也應該重新考慮你的數據類型。如果用戶輸入2和3會怎麼樣?這會給你的解決方案平均2,而不是2.5。請參閱http://stackoverflow.com/questions/7220681/division-of-integers-in-java –