Write static methods to convert Celsius to Fahrenheit and back, an overloaded average for 2 values or any number of values (varargs), and use them to print a weekly report.
Solution
Main.java
public class Main {
static double toFahrenheit(double c) { return c * 9 / 5 + 32; }
static double toCelsius(double f) { return (f - 32) * 5 / 9; }
static double average(double a, double b) { return (a + b) / 2; }
static double average(double... values) {
if (values.length == 0) return Double.NaN;
double sum = 0;
for (double v : values) sum += v;
return sum / values.length;
}
public static void main(String[] args) {
double[] week = {31.5, 29.0, 33.2, 35.1, 30.4, 28.8, 32.0};
double avg = average(week);
System.out.printf("weekly average %.2f C = %.2f F%n", avg, toFahrenheit(avg));
System.out.printf("Mon/Tue average %.2f C, 98.6 F = %.1f C, empty = %s%n", average(week[0], week[1]), toCelsius(98.6), average());
}
}
Output Verified by compiling and running
weekly average 31.43 C = 88.57 F
Mon/Tue average 30.25 C, 98.6 F = 37.0 C, empty = NaN
average(week) passes the array to the varargs version; average(a, b) uses the two-parameter overload, which is chosen first because varargs is the last resort.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!