LearnFrenzy
Sign in Take a free test

Methods and Recursion · Methods and Recursion Programs · Question 7

Temperature utility class with overloaded methods in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links