Temperature.java

mail@pastecode.io avatarunknown
java
a month ago
1.3 kB
0
Indexable
Never
public class Temperature {

    private double kelvins;
    private double celsius;
    private double fahrenheits;

    public Temperature(double kelvins, double celsius, double fahrenheits) throws Exception {
        if (!validate(kelvins, celsius, fahrenheits)) {
            throw new Exception("Invalid temperature conversion");
        }

        this.kelvins = kelvins;
        this.celsius = celsius;
        this.fahrenheits = fahrenheits;
    }
    public static boolean validate(double kelvins, double celsius, double fahrenheits) {
        double kelvinsFromC = celsius + 273.15;
        double celsiusFromK = kelvins - 273.15;
        double celsiusFromF = (fahrenheits - 32) * (5.0 / 9.0);
        double fahrenheitsFromC = celsius * (9.0 / 5.0) + 32;
    
        boolean isValid = Math.abs(celsiusFromF - celsius) < 0.5 &&
                          Math.abs(celsiusFromK - celsius) < 0.5 &&
                          Math.abs(kelvinsFromC - kelvins) < 0.5 &&
                          Math.abs(fahrenheits - fahrenheitsFromC) < 0.5;
    
        return isValid;
    }   
    public static void main(String[] args) {
        try {
            Temperature temperature = new Temperature(25, 30, 250);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
    
}