java - 如何打印第一个余额,然后是新的余额?
问题描述
我写了一个小作业,我创建了一个TimeDepositAccount
并正在创建一个方法来获取当前余额,计算利息后的新余额,然后是一个取款方法。我一直坚持打印新余额,System.out
因为由于某种原因,我无法获得新余额。其次,我想为withdraw方法使用一个局部变量,因为在我们即将进行的测试中,我们将对其进行测试,但我们从未在课堂上做过它们,所以我不确定如何去做。
public class TimeDepositAccount {
//instance fields
private double currentBalance;
private double interestRate;
//Constructors
public TimeDepositAccount(){}
public TimeDepositAccount(double Balance1, double intRate){
currentBalance = Balance1;
interestRate = intRate;
}
//Methods
public double getcurrentBalance(){
return currentBalance;
}
public void newBalance(){
currentBalance = currentBalance * (1 + (interestRate/ 100) );
}
public double getintRate(){
return interestRate;
}
public String toString(){
return "TimeDepositAccount[ currentBalance = "+getcurrentBalance()+",
interestRate = "+getintRate()+"]";
}
public class TimeDepositAccountTester{
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
System.out.print(currentBalance);
}
}
我希望输出首先打印 10.0,然后是 10.2,但我两次都得到 10.0。
解决方案
您可能希望将 main 方法更改为以下内容:
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
currentBalance = tda.getcurrentBalance();
System.out.print(currentBalance);
}
该变量currentBalance
存储您定义时的余额。改变 的余额tda
不会改变 的值currentBalance
。因此,要更新 的值currentBalance
,您需要currentBalance = tda.getcurrentBalance();
再次运行。
推荐阅读
- javascript - 将参数分配给事件是如何工作的?
- python - 在 sklearn.linear_model._logistic 中遇到问题
- c++ - 如何从控制台应用程序运行 Windows 桌面应用程序
- raml - RAML 覆盖必填字段或
- android - Jetpack Compose 卡上的事件处理
- firebase - 无法为 Firebase 部署 Cloud Functions
- reactjs - 我无法从 console.log 读取 this.props
- c++ - 如何将整个 openCV 库构建成静态库?
- xcode - 如何在 Xcode Scheme Arguments Passed On Launch 窗口中使用环境变量?
- roc - 计算 ROC 和 AUC 值: