This program takes in 10 temperatures from user input, computes the average, and then prints out the temps above average.
For some reason that I don't see, when I give the input of three temperatures (100, 90, 70 in that order) I get this output:
100 is an above average temperature.
100 is an above average temperature.
90 is an above average temperature.
But when I give this input (70, 90, 100 in that order), I get
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)
Can someone help me see what I do not?
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.");
}
}
}
}