银行卡是日常生活重要组成部分。每张银行卡信息包含账号、持卡人姓名、身份证号码、地址、存款余额。本任务只要求编写一个方法showCardInfo()完成存款、取款、查询。java代码
时间: 2024-09-23 17:01:47 浏览: 42
在Java中,我们可以创建一个BankCard类来表示银行卡的基本信息,并提供一些基本操作方法。这里是一个简单的示例,展示了如何实现`showCardInfo()`方法以及存款(deposit()), 取款(withdraw()), 查询(balanceQuery())等操作:
```java
import java.util.Scanner;
class BankCard {
private String account;
private String holderName;
private String idNumber;
private String address;
private double balance;
// 构造函数
public BankCard(String account, String holderName, String idNumber, String address) {
this.account = account;
this.holderName = holderName;
this.idNumber = idNumber;
this.address = address;
this.balance = 0.0;
}
// 显示卡片信息
public void showCardInfo() {
System.out.println("Account: " + account);
System.out.println("Holder Name: " + holderName);
System.out.println("ID Number: " + idNumber);
System.out.println("Address: " + address);
System.out.println("Balance: " + balance);
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New balance: " + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
// 取款方法
public boolean withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
return true;
} else {
System.out.println("Insufficient balance for withdrawal.");
return false;
}
}
// 查询余额方法
public double balanceQuery() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BankCard card = new BankCard("123456789", "John Doe", "1234567890123456", "123 Street");
System.out.println("Enter operation:");
System.out.println("1. Show Card Info");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Check Balance");
int choice = scanner.nextInt();
switch (choice) {
case 1:
card.showCardInfo();
break;
case 2:
System.out.println("Enter deposit amount:");
double depositAmount = scanner.nextDouble();
card.deposit(depositAmount);
break;
case 3:
System.out.println("Enter withdrawal amount:");
double withdrawAmount = scanner.nextDouble();
card.withdraw(withdrawAmount);
break;
case 4:
double balance = card.balanceQuery();
System.out.println("Current Balance: " + balance);
break;
default:
System.out.println("Invalid choice!");
}
scanner.close();
}
}
```
在这个示例中,用户可以通过输入选择不同的操作,然后按照提示进行存款、取款或查看余额。
阅读全文