In: Computer Science
Write a complete Java program, including import statements, variable declarations and initializations as needed, for the following problem. DO NOT USE ARRAYS.
The program will read from the keyboard a series of records, each record containing a city ID number (integer), morning temperature (integer) and evening temperature (integer). See below for sample input.
Sample input:
123 72 79
157 80 100
103 76 56
9999
For each city ID read in, compute the average of the two temperatures. Print a heading and below it the city ID, morning temperature, evening temperature and the average temperature (one decimal place) with columns lined up as shown below in the sample output using printf. Continue reading records until the city id is 9999.
Sample output:
City id morning evening average 123 72 79 75.5
When all records have been read in, print (a) the total number of records read in, (b) the lowest AM temperature and the associated city ID and (c) the highest average temperature (one decimal point) and the associated city ID. Don’t print the numbers by themselves (123 72); include a description to explain what the number represents. For example,
City 123 has the lowest morning temperature of 72
If the user entered 9999 as the first city, the program should print “No records read in”.
Program Code [JAVA]
import java.util.Scanner;
public class City {
public static void main(String[] args) {
// Object of Scanner class to take input
Scanner scan = new Scanner(System.in);
// Declaring All required variables
int cityID, morningTemp, eveningTemp, totalRecords = 0;
double avgTemp;
int lowestAMTemp = 0, lowestTempCity = 0;
double highestAvgTemp = 0.0;
int highestAvgCity = 0;
// Taking input from user until he enters 9999
while(true) {
cityID = scan.nextInt();
if(cityID == 9999) {
// Checking if it is first record to read
if(totalRecords == 0)
System.out.println("No records to read in");
break;
}
morningTemp = scan.nextInt();
eveningTemp = scan.nextInt();
if (totalRecords == 0) {
lowestTempCity = cityID;
lowestAMTemp = morningTemp;
}
// Calculating Average temperature
avgTemp = (morningTemp + eveningTemp) / 2.0;
// Identifying lowest AM adn highest Avg
if(morningTemp < lowestAMTemp) {
lowestAMTemp = morningTemp;
lowestTempCity = cityID;
}
if(avgTemp > highestAvgTemp) {
highestAvgTemp = avgTemp;
highestAvgCity = cityID;
}
// Printing number
System.out.printf("City id morning evening average %d %d %d %.1f", cityID, morningTemp, eveningTemp, avgTemp);
totalRecords++;
}
System.out.println("\nTotal number of records: " + totalRecords);
System.out.println("City " + lowestTempCity + " has the lowest morning temperature of " + lowestAMTemp);
System.out.printf("City %s has the highest average temperature of %.1f",highestAvgCity, highestAvgTemp);
}
}
Sample Output:-
-------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERIES!!!
HIT A THUMBS UP IF YOU DO LIKE IT!!!