java - Java 实例变量设置为 0
问题描述
我是了解Java的新手,所以请原谅我的无知。我编译了以下代码:
import java.lang.Math;
public class Main{
double initialBalance;
double interestRate;
double years;
public static final double periodsPerYear = 12;
//constructer
public Main(double balance, double interest, double life){
}
//methods
double getMonthlyPayment(){
return Math.round(initialBalance * ((interestRate/periodsPerYear)+((interestRate/periodsPerYear)/(Math.pow(1+(interestRate/periodsPerYear),periodsPerYear*years)-1)))*100.00)/100.00;
}
//main method
public static void main(String[] args){
double initialBalance = 10000;
double interestRate = 0.05;
double years = 2;
Main loan = new Main( initialBalance, interestRate, years );
System.out.println(initialBalance);
System.out.println(interestRate);
System.out.println(years);
System.out.println(loan.getMonthlyPayment());
}
}
问题是当我需要返回 438.71 时,“System.out.println(loan.getMonthlyPayment())”行返回 0.0。我究竟做错了什么?
解决方案
在对象的初始化中:
Main loan = new Main(initialBalance, interestRate, years);
这个构造函数被称为:
public Main(double balance, double interest, double life){
}
但它什么也没做。它是空的。您需要在构造函数中设置实例变量,如下所示:
public Main(double balance, double interest, double life){
this.initialBalance = balance;
this.interestRate = interest;
this.years = life;
}
推荐阅读
- amazon-dynamodb - AWS rekognition 可以检测图像中的表并允许我摄取到 dynamoDB 表中吗
- java - Java中有没有隐式使用反射?
- r - 如何从 R 关闭浏览器窗口?
- java - 如何在 Android 的 RelativeLayout 中使用 ScrollView?
- ng-bootstrap - 获取对嵌套在模式中的元素的引用
- javascript - 用JS提交表单并仍然成功发布所有表单数据的正确方法是什么?
- javascript - 组件在 React 中没有响应
- aws-api-gateway - 自定义授权方返回 403 但不调用 lambda
- css - 单选按钮看起来像按钮
- c++ - C++ 缓存,根据项目的“价值”驱逐项目