用Java创建一个银行取钱的代码,要求代码不能过短
时间: 2024-04-29 07:25:07 浏览: 101
以下是一个简单的Java代码示例,用于银行取钱:
```
import java.util.Scanner;
public class Bank {
private double balance;
public Bank(double initialBalance) {
balance = initialBalance;
}
public void withdraw(double amount) {
if (amount > balance) {
System.out.println("Insufficient funds.");
} else {
balance -= amount;
System.out.println("$" + amount + " has been withdrawn from your account.");
}
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your initial balance:");
double initialBalance = scanner.nextDouble();
Bank bank = new Bank(initialBalance);
System.out.println("Your current balance is $" + bank.getBalance());
System.out.println("Enter the amount you wish to withdraw:");
double amount = scanner.nextDouble();
bank.withdraw(amount);
System.out.println("Your new balance is $" + bank.getBalance());
}
}
```
该代码创建了一个Bank类,其中包含了一个存款余额变量和一个取款方法。在main方法中,创建了一个Bank对象,并让用户输入初始余额和要取款的金额。然后,调用Bank对象的withdraw方法进行取款,并打印出新的余额。
注意:此代码是一个简单的示例,实际的银行系统应该包含更多的安全措施和验证。
阅读全文