【发布时间】:2014-12-11 05:30:03
【问题描述】:
要求: 编写一个类 BankAccount,它有两个实例变量,分别代表所有者的名称(String 类型)和余额(double 类型)。向这个类添加以下方法:
- 将 BankAccount 实例变量初始化为两个参数中的值的构造函数,所有者的名称和初始余额 (>=0.0)。
- deposit:给定金额 (>0.0) 存入,此方法将其存入帐户。
- withdraw:给定一个金额(>0.0 和
- getName:此方法返回所有者名称。
- getBalance:此方法返回第 t 个当前余额。 (不要尝试格式化数字 - 只需采用默认值即可。)
在您的方法中包括适当的检查,以确保存入和提取的金额满足指定的限制条件。使用良好的封装指南。
我是否正确解释并正确执行它,如果不是,需要修复什么以及如何修复。任何帮助表示赞赏。
代码:
import java.util.*;
public class BankAccount {
static Scanner in = new Scanner (System.in);
private static String name;
private static double balance;
public BankAccount(String n, double b){
System.out.println("Enter your name: ");
n = in.nextLine();
name = n;
System.out.println("Enter your current balance: ");
b = in.nextDouble();
balance = b;
}
public void deposit(){
System.out.println("Enter the amount you would like to deposit: ");
double deposit = in.nextDouble();
if(deposit > 0.0){
balance = balance + deposit;
}
}
public void withdraw(){
System.out.println("Enter the amount you would like to withdraw: ");
double withdraw = in.nextDouble();
if(withdraw > 0.0 && withdraw <= balance){
balance = balance - withdraw;
}
}
public static String getName(){
return name;
}
public static double getBalance(){
return balance;
}
}
【问题讨论】:
-
不太确定该类是否应该提示用户他们想要存款/取款的金额,您应该将值传递给这些方法...
-
理想情况下,您必须从变量和方法声明中删除 static 关键字。如果您有静态变量,则不需要 getter。此外,静态名称和余额意味着所有 BankAccounts 将具有相同的名称和余额。