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를 주입하세요.

+ Recent posts