반환 타입이 있는 클래스 메서드 추가하기
자동차에는 연료 소비율을 나타내는 miles per gallon이라는 성능 지표가 있어요. calculateMPG라는 메서드를 만들어 miles per gallon을 계산해 봅시다. calculateMPG 메서드는 주행한 마일 수와 사용한 갤런 수를 사용해 올바른 miles per gallon 값을 계산하여 반환합니다.
이 연습은 강의의 일부입니다
Java로 배우는 객체 지향 프로그래밍 입문
연습 안내
int타입을 반환하는calculateMPG메서드를 만드세요.calculateMPG메서드는 두 개의 매개변수를 받아야 합니다:intmilesDriven와intgallonsUsed.calculateMPG는milesDriven을gallonsUsed로 나눈 결과를 반환해야 합니다.myCar객체 인스턴스를 사용해 매개변수 값180과20으로calculateMPG메서드를 호출하고, 그 반환 값을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
class Main {
static class Car {
String color;
String model;
int year;
Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
}
void turnEngineOn() {
System.out.println("engine is on");
}
// Create the calculateMPG method
____ calculateMPG(int ____, int ____) {
return ____ / ____;
}
}
public static void main(String[] args) {
Car myCar = new Car("red", "camry", 2022);
// Print out value for when calculateMPG is used
System.out.println(myCar.calculateMPG(____, ____));
}
}