提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
私有实例变量和公共方法
public class Main { public static void main(String[] args) { MyCredit ac = new MyCredit(); double balance = ac.getBalance();/**from n o w j a v a . c o m**/ System.out.println("Balance = " + balance); ac.credit(24.718); ac.debit(10.112); balance = ac.getBalance(); System.out.println("Balance = " + balance); // Attempt to credit and debit invalid amounts ac.credit(-24.90); ac.debit(Double.POSITIVE_INFINITY); balance = ac.getBalance(); System.out.println("Balance = " + balance); // Attempt to debit more than the balance ac.debit(200.00); // from N o w J a v a . c o m - 时代Java balance = ac.getBalance(); System.out.println("Balance = " + balance); } } class MyCredit { private double balance; // Return the balance of this account public double getBalance() { return this.balance; } public int credit(double amount) { if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) { System.out.println("Invalid credit amount: " + amount); return -1; } System.out.println("Crediting amount: " + amount); this.balance = this.balance + amount; return 1; } public int debit(double amount) { if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) { System.out.println("Invalid debit amount: " + amount); return -1; }