怎么用Java写出银行存取款的代码
时间: 2023-05-30 22:05:46 浏览: 893
以下是一个简单的Java程序,实现了银行存取款的功能:
```
import java.util.Scanner;
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("余额不足!");
}
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入初始存款金额:");
double initialBalance = input.nextDouble();
BankAccount account = new BankAccount(initialBalance);
while (true) {
System.out.println("请选择操作:");
System.out.println("1. 存款");
System.out.println("2. 取款");
System.out.println("3. 查询余额");
System.out.println("4. 退出");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.print("请输入存款金额:");
double depositAmount = input.nextDouble();
account.deposit(depositAmount);
System.out.println("存款成功!");
break;
case 2:
System.out.print("请输入取款金额:");
double withdrawAmount = input.nextDouble();
account.withdraw(withdrawAmount);
System.out.println("取款成功!");
break;
case 3:
System.out.println("当前余额为:" + account.getBalance());
break;
case 4:
System.out.println("感谢使用本系统!");
System.exit(0);
default:
System.out.println("输入错误,请重新选择!");
break;
}
}
}
}
```
在程序中,BankAccount类表示银行账户,包含了存款、取款、查询余额等操作。在main方法中,使用Scanner类获取用户输入的操作选择和金额,然后调用BankAccount类的方法进行相应的操作。程序使用无限循环,直到用户选择退出为止。
阅读全文