Java 문제 객체 지향으로 계좌 만들어보기
은행 계좌를 만드는 것을 객체 지향 방식으로 설계해보기
요구사항
- Account 클래스 만들기
- int balance 잔액
- deposit: 입금 메소드
- 파라미터 int amount
- withdraw 출금 메소드
- 파라미터 int amount
- 잔액 부족시 "잔액이 부족합니다." 출력
- showBalance 잔고 보여주기
- "잔고: " 출력 후 남은 잔고량 보여주기
- 메인 프로그램 시작하기
- Account 클래스 인스턴스 생성하기
- deposit 메소드로 계좌에 10000원 입금하기
- withdraw 메소드로 계좌에 9000원 출금하기
- withdraw 메소드로 계좌에 2000원 출금하여 "잔액이 부족합니다." 출력 확인하기
- 잔고 출력하기.
문제 풀이
클래스를 객체 지향으로 만든 후 메인 프로그램을 시작하도록 한다.
class
public class Class {
int balance; // 잔고
void deposit(int amount)
{
balance = balance + amount;
}
void withdraw(int amount) {
if (balance >= amount) {
balance = balance - amount;
} else {
System.out.println("잔액이 부족합니다.");
}
}
void showBalance() {
System.out.println("잔고: " + balance);
}
}
main
public class Main {
public static void main(String[] args) {
Class amount = new Class();
amount.deposit(10000);
amount.withdraw(9000);
amount.withdraw(2000);
amount.showBalance();
}
}
실행 결과:
잔액이 부족합니다.
잔고: 1000