将public void方法变量转换为私有方法?

时间:2014-04-11 18:30:56

标签: java

对于我正在做的项目,我需要以这种方式构建我的代码。但是,calcMonthlyStatement上的return语句返回NaN(不是数字)值。我假设这是因为我在每月付款方程中将0除以0。我不确定如何将我的public void方法中的变量及其值导入我的私有方法。

    import java.text.*;
    import java.util.*;
    import java.lang.Math.*;
    public class Mortgage{
        private Scanner s = new Scanner(System.in);
        private double principal;
        private double monthlyInt;
        private double numOfMonths; 
        private double monthlyPayment;
        private double totalPayment;
        Random rand = new Random();
        private int rng = rand.nextInt(9900) + 100;

    public void storeLoanAmount(double loanAmt){
        principal = loanAmt;
    }

    public void storeTerm(double term){
        numOfMonths = term;
    }


    public void storeInterestRate(double intRte){
        monthlyInt = intRte;
    }

    private double calcMonthlyPayment(){
        monthlyPayment = principal*((monthlyInt*(Math.pow((1+monthlyInt),numOfMonths)))/((Math.pow(1+monthlyInt,numOfMonths))-1));
        return monthlyPayment;
    }
    public String toString(){
         Mortgage call = new Mortgage();
         double mPayment = call.calcMonthlyPayment(); 
         String stats = ("Account number: " + rng +"\nThe monthly payment is $" + mPayment);
         return stats;
    }


//my main class from a seperate .java file

    public class MortgageEF{

public static void main(String[] args){
    Mortgage mort = new Mortgage();
    double principle = 100000;
    double numOfMonths = (15*12);
    double monthlyInt = ((5.5)/12);

    mort.storeLoanAmount(principle);
    mort.storeTerm(numOfMonths);
    mort.storeInterestRate(monthlyInt);

    System.out.print(mort.toString());
}

}

1 个答案:

答案 0 :(得分:0)

问题是您正在使用错误的对象。

public String toString(){
     Mortgage call = new Mortgage();
     double mPayment = call.calcMonthlyPayment(); 
     String stats = ("Account number: " + rng +"\nThe monthly payment is $" + mPayment);
     return stats;
}

main中的代码会创建一个新的Mortgage,并进行设置字段的方法调用。但是在上面的代码中,您不是使用此对象中的字段,而是创建一个 Mortgage对象,然后在所有字段中都有0个对象;然后你在那个新对象上调用calcMonthlyPayment,它返回NaN,因为它将使用call中仍为0的字段,而不是this对象中的字段,其字段包含正确的数据。

toString没有理由创建新对象:

     //Mortgage call = new Mortgage();
     double mPayment = calcMonthlyPayment();