Encapsulation

Lab Java Beginner 10 points

Create BankAccount with a private double balance, a getter, and methods deposit and withdraw that reject non-positive amounts and overdrafts with the message rejected. Process commands and print the final balance with 2 decimals.

Input

n, then n lines: deposit X or withdraw X.

Output

Any rejected lines, then the balance.

Example

Input

5
deposit 100
withdraw 30.5
withdraw 500
deposit -5
deposit 10

Output

rejected
rejected
79.50
Sample input available Sample output available
Editor
Java

Hints

private fields can only be changed through the class's own methods.

Solution explanation

Encapsulation means outside code can't put the object into an invalid state, like a negative balance.

Show solution
import java.util.Scanner;

class BankAccount {
    private double balance;

    double getBalance() {
        return balance;
    }

    boolean deposit(double amount) {
        if (amount <= 0) {
            return false;
        }
        balance += amount;
        return true;
    }

    boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        BankAccount acc = new BankAccount();
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            String cmd = sc.next();
            double amount = sc.nextDouble();
            boolean ok = cmd.equals("deposit") ? acc.deposit(amount) : acc.withdraw(amount);
            if (!ok) {
                System.out.println("rejected");
            }
        }
        System.out.printf("%.2f%n", acc.getBalance());
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD