java模拟银行存取款业务代码
时间: 2023-07-10 17:18:51 浏览: 165
好的,以下是一个简单的Java代码示例,用于模拟银行存取款业务:
```java
import java.util.Scanner;
public class BankAccount {
private double balance;
//构造函数
public BankAccount() {
balance = 0;
}
//存款
public void deposit(double amount) {
balance += amount;
}
//取款
public void withdraw(double amount) {
balance -= amount;
}
//获取余额
public double getBalance() {
return balance;
}
//主函数
public static void main(String[] args) {
BankAccount account = new BankAccount();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请选择操作:1.存款 2.取款 3.查询余额 4.退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入存款金额:");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
System.out.println("存款成功!");
break;
case 2:
System.out.println("请输入取款金额:");
double withdrawAmount = scanner.nextDouble();
if (withdrawAmount > account.getBalance()) {
System.out.println("余额不足,取款失败!");
} else {
account.withdraw(withdrawAmount);
System.out.println("取款成功!");
}
break;
case 3:
System.out.println("当前余额为:" + account.getBalance());
break;
case 4:
System.out.println("谢谢使用!");
System.exit(0);
break;
default:
System.out.println("输入有误,请重新选择!");
break;
}
}
}
}
```
这个程序中,我们定义了一个BankAccount类,实现了存款、取款和查询余额等功能。在主函数中,我们使用Scanner类接收用户输入,并根据用户选择执行不同的操作。
阅读全文