写java代码 【问题描述】模拟用钱包购买商品的行为。要求实现一个钱包报警异常类,钱包类,信用卡类以及主类,当钱包现金不够支付的时候用信用卡支付,如果信用卡也不够支付则不够买该商品 【输入形式】 主类首先输入钱包中现金数量,精确到小数点后两位 第二行输入信用卡的信用额度 第三行输入信用卡已透支的额度 第四行开始输入支付额度直到输入字符串或钱包不能支付为止为止 【输出形式】输出支付信息 【样例输入】 2000 5000 1000 500 2300 4000 【样例输出】 Cash payments:500.00,Remaining cash:1500.00,Credit card availability:4000.00 Cash payments:1500.00,Remaining cash:0.00,Credit card availability:4000.00 Credit card payments:800.00,Remaining cash:0.00,Credit card availability:3200.00 Wallet Exception,Insufficient credit card balance to pay!
时间: 2024-02-11 11:06:42 浏览: 59
好的,根据您的问题描述,我可以提供以下Java代码实现:
```java
class WalletException extends Exception {
public WalletException(String message) {
super(message);
}
}
class Wallet {
private double cash;
public Wallet(double cash) {
this.cash = cash;
}
public void payCash(double amount) throws WalletException {
if (cash < amount) {
throw new WalletException("Insufficient cash balance to pay!");
}
cash -= amount;
System.out.printf("Cash payments:%.2f,Remaining cash:%.2f,", amount, cash);
}
public void payCreditCard(double amount, CreditCard creditCard) throws WalletException {
if (creditCard.availableBalance() < amount) {
throw new WalletException("Insufficient credit card balance to pay!");
}
creditCard.pay(amount);
System.out.printf("Credit card payments:%.2f,Remaining cash:%.2f,Credit card availability:%.2f,", amount, cash, creditCard.availableBalance());
}
}
class CreditCard {
private double creditLimit;
private double creditUsed;
public CreditCard(double creditLimit, double creditUsed) {
this.creditLimit = creditLimit;
this.creditUsed = creditUsed;
}
public double availableBalance() {
return creditLimit - creditUsed;
}
public void pay(double amount) throws WalletException {
if (availableBalance() < amount) {
throw new WalletException("Insufficient credit card balance to pay!");
}
creditUsed += amount;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double cash = scanner.nextDouble();
double creditLimit = scanner.nextDouble();
double creditUsed = scanner.nextDouble();
Wallet wallet = new Wallet(cash);
CreditCard creditCard = new CreditCard(creditLimit, creditUsed);
while (scanner.hasNextDouble()) {
try {
double amount = scanner.nextDouble();
wallet.payCash(amount);
} catch (WalletException e1) {
try {
wallet.payCreditCard(amount, creditCard);
} catch (WalletException e2) {
System.out.println(e2.getMessage());
break;
}
}
}
System.out.println("Wallet Exception,No more payments to make!");
}
}
```
主要思路与Python代码类似,使用了三个类,分别是`Wallet`(钱包类)、`CreditCard`(信用卡类)和`WalletException`(钱包报警异常类)。其中,钱包类和信用卡类分别定义了现金支付和信用卡支付的方法,并在支付时进行余额判断,如余额不足则抛出钱包异常类。主程序中,先输入钱包中现金数量、信用卡的信用额度和信用卡已透支的额度,然后循环输入支付额度,直到输入字符串或钱包不能支付为止。在循环中,先尝试使用钱包支付,如余额不足则使用信用卡支付,如信用卡余额也不足则抛出钱包异常类。最后,如果循环正常结束,则输出“Wallet Exception,No more payments to make!”。
阅读全文