- 클래스 변수와 클래스 메소드를 이해하기
문제
상수
- static final 변수 만들기
- 1 파운드 = 0.45359237 킬로그램
- 1 인치 = 2.54 센티미터
- 위의 두 공식을 이용하여 상수 네 개 만들기
- KILOGRAMS_PER_POUND / POUNDS_PER_KILOGRAM / CENTIMETERS_PER_INCH / INCHES_PER_CENTIMETER
- 예시
public static final double KILOGRAMS_PER_POUND = 0.45359237;
클래스 메소드
- 앞서 만든 상수들을 활용하여 무게와 길이 단위를 전환하는 메소드 만들기
- 추가로 섭씨에서 화씨로, 화씨에서 섭씨로 전환하는 메소드도 만들기
- 섭씨를 화씨로 전환하는 수학적 공식 :
°F = °C × (9 / 5) + 32
- 화씨를 섭씨로 전환하는 수학적 공식 :
°C = (°F − 32) x (5 / 9)
private 생성자
- UnitConverter 클래스는 인스턴스를 만들지 않고, static한 방법으로만 사용할 것
- UnitConverter 클래스의 생성자를 private로 선언하여 인스턴스 생성을 막기
결과값
35 lb -> 15.88 kg
62 kg -> 136.69 lb
12.2 in -> 30.99 cm
3.82 cm -> 1.50 in
48 °F -> 8.89 °C
-9 °C -> 15.80 °F
풀이 및 답
UnitConverter 클래스
public class UnitConverter {
public static final double KILOGRAMS_PER_POUND = 0.45359237;
public static final double POUNDS_PER_KILOGRAM = 1 / KILOGRAMS_PER_POUND;
public static final double CENTIMETERS_PER_INCH = 2.54;
public static final double INCHES_PER_CENTIMETER = 1 / CENTIMETERS_PER_INCH;
public static int celsius = 0; // 섭씨
public static int fahrenheit = 0; // 화씨
private UnitConverter(){
}
public static double toPounds(double kilograms){
// 파라미터로 받은 kilograms를 pound 단위로 바꾸어주는 클래스 메소드
return POUNDS_PER_KILOGRAM * kilograms;
}
public static double toKilograms(double pounds) {
// 파라미터로 받은 pounds를 kilogram 단위로 바꾸어주는 클래스 메소드
return KILOGRAMS_PER_POUND * pounds;
}
public static double toCentimeters(double inches) {
// 파라미터로 받은 inch를 centimeter 단위로 바꾸어주는 클래스 메소드
return CENTIMETERS_PER_INCH * inches;
}
public static double toInches(double centimeters) {
// 파라미터로 받은 centimeter를 inch 단위로 바꾸어주는 클래스 메소드
return INCHES_PER_CENTIMETER * centimeters;
}
public static double toFahrenheit(double celsius) {
// 파라미터로 받은 celsius(섭씨)를 fahrenheit(화씨) 단위로 바꾸어주는 클래스 메소드
return celsius * (9.0 / 5) + 32;
}
public static double toCelsius(double fahrenheit) {
// 파라미터로 받은 fahrenheit(화씨)를 celsius(섭씨) 단위로 바꾸어주는 클래스 메소드
return (fahrenheit - 32) * (5.0 / 9);
}
}
Main 클래스
public class Main {
public static void main(String[] args) {
System.out.format("35 lb -> %.2f kg\n", UnitConverter.toKilograms(35));
System.out.format("62 kg -> %.2f lb\n", UnitConverter.toPounds(62));
System.out.format("12.2 in -> %.2f cm\n", UnitConverter.toCentimeters(12.2));
System.out.format("3.82 cm -> %.2f in\n", UnitConverter.toInches(3.82));
System.out.format("48 °F -> %.2f °C\n", UnitConverter.toCelsius(48));
System.out.format("-9 °C -> %.2f °F\n", UnitConverter.toFahrenheit(-9));
}
}