Write a Java program that contains a method named DisplayTemperature. The argume
ID: 3808647 • Letter: W
Question
Write a Java program that contains a method named DisplayTemperature. The argument to this method is the number of days and the temperature on the first day. The method is used to decrease the temperature by two degree every day in the first half of a given period and increase by one degree in the second half. If the number of days in a specified period is odd, the first half will be considered a day less than the second half. The method then displays a table showing the days and the temperatures on those days (as shown below).
The main method in the program will first ask the users to enter the number of days in the specified period and the temperature on the first day (as shown below). The program should then call the DisplayTemperature method that outputs the table (as shown below).
For example, if a user enters as follows:
Number of days in the period: 11
Temperature on the first day: -10
The method should display the following:
day temperature
1 -10
2 -12
3 -14
4 -16
5 -18
6 -17
7 -16
8 -15
9 -14
10 -13
11 -12
Explanation / Answer
import java.util.*; //Importing package.
public class Temperature {
public static void DisplayTemperature(int no_of_days, float temp){
int i, fhalf, lhalf;
//Checking if period has even or odd no. of days.
if(no_of_days % 2 == 0)
fhalf = no_of_days / 2;
else
fhalf = no_of_days / 2;
//Calculating and printing the data.
System.out.println(" Day Temperature ");
System.out.println("1 - " + temp);
for(i = 2; i <= fhalf; i++){
temp -= 2;
System.out.println(i + " - " + temp);
}
for(i = fhalf + 1; i <= no_of_days; i++){
temp += 1;
System.out.println(i + " - " + temp);
}
}
public static void main(String args[])
{
Scanner read = new Scanner(System.in); //Creating scanner object to read input.
int no_of_days;
float temp;
System.out.println(" No. of days in the specified period: ");
no_of_days = read.nextInt(); //Reading input using scanner object.
System.out.println(" Temperature on the first day: ");
temp = read.nextFloat();
DisplayTemperature(no_of_days, temp); //Calling function DisplayTemperature
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.