Java Reference
In-Depth Information
temps[i] = console.nextInt();
sum += temps[i];
}
Notice that you're now testing whether the index is strictly less than numDays . After
this loop executes, you compute the average as we did before. Then you write a new
loop that counts how many days were above average using our standard traversing loop:
int above = 0;
for (int i = 0; i < temps.length; i++) {
if (temps[i] > average) {
above++;
}
}
In this loop the test involves temps.length . You could instead have tested
whether the variable is less than numDays ; either choice works in this program
because they should be equal to each other.
If you put these various code fragments together and include code to report the
number of days that had an above-average temperature, you get the following com-
plete program:
1 // Reads a series of high temperatures and reports the
2 // average and the number of days above average.
3
4 import java.util.*;
5
6 public class Temperature2 {
7 public static void main(String[] args) {
8 Scanner console = new Scanner(System.in);
9 System.out.print("How many days' temperatures? ");
10 int numDays = console.nextInt();
11 int [] temps = new int [numDays];
12
13 // record temperatures and find average
14 int sum = 0;
15 for ( int i = 0; i < numDays; i++) {
16
System.out.print("Day " + (i + 1) + "'s high temp: ");
17
temps[i] = console.nextInt();
18
sum += temps[i];
19 }
20 double average = ( double ) sum / numDays;
21
22 // count days above average
23 int above = 0;
Search WWH ::




Custom Search