public class BankCard { private String cardNumber; private String cardHolderName; private double balance; public BankCard(String cardNumber, String cardHolderName, double balance) { this.cardNumber = cardNumber; this.cardHolderName = cardHolderName; this.balance = balance; } public String getCardNumber() { return cardNumber; } public String getCardHolderName() { return cardHolderName; } public double getBalance() { return balance; } public boolean consume(double amount) { if (amount <= balance) { balance -= amount; return true; } else { return false; } } } public class Main { public static void main(String[] args) { BankCard card = new BankCard("1234 5678 9012 3456", "张三", 1000.0); System.out.println("卡号:" + card.getCardNumber()); System.out.println("持卡人姓名:" + card.getCardHolderName()); System.out.println("余额:" + card.getBalance()); double amount = 500.0; if (card.consume(amount)) { System.out.println("消费 " + amount + " 元成功,余额:" + card.getBalance()); } else { System.out.println("余额不足,无法消费 " + amount + " 元,余额:" + card.getBalance()); } } }注释
时间: 2024-04-28 14:26:20 浏览: 96
Card.io 最新Android完整源码
这段代码是一个简单的银行卡模拟程序,包含一个 BankCard 类和一个 Main 类。BankCard 类有三个私有属性:卡号、持卡人姓名和余额,以及一个 consume 方法,用于消费。Main 类主要用于测试 BankCard 类的功能,创建一个 BankCard 对象,并调用其方法打印出卡号、持卡人姓名和余额。然后模拟消费操作,如果余额足够则消费成功并打印出余额,否则消费失败并打印出余额。
阅读全文