본문 바로가기

IT/연습문제

클래스 연습문제 풀어보기(은행계좌)

반응형

문제

 

은행 계좌 객체인 Account 객체는 잔고(balance) 필드를 가지고 있다. balance 필드는 음수값이 될 수 없고, 최대 백만원까지만 저장할 수 있다. 외부에서 balance 필드를 마음대로 변경하지 못하도록 하고, 0 <= balance <= 1,000,000 범위의 값만 가질 수 있도록 Account 클래스를 작성해보자.

 

조건

1. Setter와 Getter를 이용할 것

2. 0과 1,000,000은 MIN_BALANCE와 MAX_BALANCE 상수를 선언해서 이용할 것.

3. Setter의 매개값이 음수이거나 백만원을 초과하면 현재 balance 값을 유지.

 

[Account.java]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Account {
    final static int MIN_BALANCE = 0;
    final static int MAX_BALANCE = 1000000;
    int balance = 0;
    
    public int getBalance() {
        return balance;
    }
    public void setBalance(int balance) {
        if (balance >= MIN_BALANCE && balance <= MAX_BALANCE) {
            this.balance = balance;
        } else {
            return;
        }
    }
 
}
 
cs

 

[AccountExample.java]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class AccountExample {
 
    public static void main(String[] args) {
        Account account = new Account();
        
        account.setBalance(10000);
        System.out.println("현재 잔고 : "+ account.getBalance());
        
        account.setBalance(-100);
        System.out.println("현재 잔고 : "+ account.getBalance());
        
        account.setBalance(2000000);
        System.out.println("현재 잔고 : "+ account.getBalance());
        
        account.setBalance(300000);
        System.out.println("현재 잔고 : "+ account.getBalance());
 
    }
 
}
 
 
cs

 

결과 화면

 

 

반응형