Please complete this simple Java program: 1. Create an array that will store 7 d
ID: 3823826 • Letter: P
Question
Please complete this simple Java program:
1. Create an array that will store 7 different temperatures
2. Populate the array with 7 random temperaturs ranging from 1 to 100 degrees (USE A LOOP AND A RANDOM NUMBER GENERATOR OBJECT)
3. Once the 7 temperatures are in the array, calculate the average of the 7 temperatures in the array and print out the average
4. then print out each temperature in a statment comparing the temperature to the average such as :
"The average temperature is 48.94"
"Temperature 1 is 20 and is below average"
"temperature 2 is is 65 and is above average"
etc...
Explanation / Answer
CalAvgTemperatures.java
import java.util.Random;
public class CalAvgTemperatures {
public static void main(String[] args) {
//Creating an random Class object
Random r = new Random();
//Creatig an integer type temperature array of size 7
int temp[]=new int[7];
/* generating the random temperatures between 1-100
* and populating those values into an array
*/
for(int i=0;i<temp.length;i++)
{
temp[i]=r.nextInt(100) +1;
}
//calling the method by passing the temperature array as argument
double avgTemp=calAvg(temp);
//displaying the average temperature
System.out.printf("The average temperature is :%.2f ",avgTemp);
//Displaying which temperature is above or below average temperature array
for(int i=0;i<temp.length;i++)
{
if(temp[i]<avgTemp)
System.out.println("Temperature "+(i+1)+" is "+temp[i]+" and is below average");
else if(temp[i]>avgTemp)
System.out.println("Temperature "+(i+1)+" is "+temp[i]+" and is above average");
}
}
//This method will calculate the average temperature of an array
private static double calAvg(int[] temp) {
double sum=0.0,avg=0.0;
for(int i=0;i<temp.length;i++)
{
//calculating the sum
sum+=temp[i];
}
//calculating the average
return sum/temp.length;
}
}
_____________________
Output:
The average temperature is :58.71
Temperature 1 is 60 and is above average
Temperature 2 is 48 and is below average
Temperature 3 is 72 and is above average
Temperature 4 is 17 and is below average
Temperature 5 is 68 and is above average
Temperature 6 is 62 and is above average
Temperature 7 is 84 and is above average
______________ThankYou
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.