I am trying to write a program that takes in the number of days and stores the temperature of each day in an array. The size of the array i.e. number of days is user-defined. I want to calculate the average temperature of all the days and print the number of days that have a temperature greater than average. However, my Average method does not seem to work.
All it does it print array and stops.
class Main {
public static Scanner scanner=new Scanner(System.in);
public static int[] temperatures=null;
public static void main(String[] args) {
System.out.println("How many days temperature?");
int no_of_days=scanner.nextInt();
temperatures=new int[no_of_days];
int i=0;
while(i<no_of_days){
System.out.println("Day "+(i+1)+"'s "+"highest temperature:");
temperatures[i]=scanner.nextInt();
i=i+1;
}
System.out.println(Arrays.toString(temperatures));
Average(temperatures);
}
This is the Average method. It is not returning anything but simply prints the no. of days
public static void Average(int[] atemperatures){
int average=0;
int i=0;
int sum=atemperatures[0];
while(i<=atemperatures.length-2){
sum=sum+atemperatures[i+1];
}
average=(sum/atemperatures.length);
System.out.println("The average temperature is:"+average);
int count=0;
for(int j=0;j<atemperatures.length;j++){
if(atemperatures[j]>average){
count++;
}
}
System.out.println(count+"day's above average");
}
}
>Solution :
Because you have an infinite loop with
while(i<=atemperatures.length-2){
sum=sum+atemperatures[i+1];
}
You forgot to increment i.
while(i<=atemperatures.length-2){
sum=sum+atemperatures[i+1];
i++;
}
You could also use a for-each loop. Which is a lot easier to reason about. Like,
int sum = 0;
for (int temp : atemperatures) {
sum += temp;
}