首页 > 解决方案 > 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。我究竟做错了什么?

标签: java

解决方案


在对象的初始化中:

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;
}

推荐阅读