return문 (Class)
package sec08.exam02_return;
public class Car {
//필드
int gas;
//생성자 - 기본생성자 사용
//메소드
void setGas(int gas) { //리턴값이 없는 메소드 -> 매개값을 받아서 gas에 저장
this.gas = gas;
}
boolean isLeftGas() { //리턴값이 boolean인 메소드
if(gas == 0) { //gas가 없으면 (gas == 0)
System.out.println("gas가 없습니다.");
return false; //isLeftGas()=false
}
System.out.println("gas가 있습니다."); //gas가 있으면 (gas != 0)
return true; //isLeftGas()=true
}
void run() { //리턴값이 없는 메소드
while(true) {
if(gas > 0) {
System.out.println("달립니다. (gas잔량: " + gas + ")");
gas -= 1; //5 4 3 2 1
} else { //gas가 0이되면
System.out.println("멈춥니다. (gas잔량: " + gas + ")");
return; //메소드 실행 종료
}
}
}
}
return문 (실행문)
package sec08.exam02_return;
public class CarExample {
public static void main(String[] args) {
Car myCar = new Car();
myCar.setGas(5); //Car의 setGas() 메소드 호출
boolean gasState = myCar.isLeftGas(); //Car의 isLeftGas() 메소드 호출
if(gasState) { //gas가 있으면 isLeftGas()=true
System.out.println("출발합니다.");
myCar.run(); //Car의 run() 메소드 호출
}
if(myCar.isLeftGas()) {
System.out.println("gas를 주입할 필요가 없습니다."); //isLeftGas()=true일 때
} else {
System.out.println("gas를 주입하세요."); //isLeftGas()=false일 때
}
}
}
gas가 있습니다.
출발합니다.
달립니다. (gas잔량: 5)
달립니다. (gas잔량: 4)
달립니다. (gas잔량: 3)
달립니다. (gas잔량: 2)
달립니다. (gas잔량: 1)
멈춥니다. (gas잔량: 0)
gas가 없습니다.
gas를 주입하세요.
'Java > 6. 클래스 (Class)' 카테고리의 다른 글
Day 7 : 클래스 외부에서 메소드 호출 (0) | 2021.10.27 |
---|---|
Day 7 : 클래스 내부에서 메소드 호출 (0) | 2021.10.27 |
Day 7 : 매개 변수의 수를 모를 경우 (매개 변수를 배열 타입으로 선언) (0) | 2021.10.27 |
Day 7 : 메소드 선언 및 호출 (0) | 2021.10.27 |
Day 7 : 다른 생성자를 호출해서 중복 코드 줄이기 (0) | 2021.10.27 |