有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java访问同一类中dif方法中的值

我试图在类中创建一个计算贷款金额的方法。这个方法应该返回“totalPay”,但它说它没有被声明,你知道为什么吗

public loan(double anualInterestRate, int numberOfYears, double loanAmount){

    double base = (double) ( loanAmount * (1+anualInterestRate/12));
    double exponent = (double) (numberOfYears * 12);
    double totalPay = (double) Math.pow(base, exponent); 
}

由于某种原因,总付款方式没有看到“totalPay”:

/**
 * 
 * @return total payment
 */
public double totalPayment(){
    return totalPay;
}

共 (1) 个答案

  1. # 1 楼答案

    您正在构造函数中声明变量,使它们仅在构造函数中可见。不要这样做。在类中声明需要类可见性的类

    class Loan {
        private double base;
        private double exponent;
        private double totalPay;
    
        public Loan(double anualInterestRate, int numberOfYears, double loanAmount){
    
            base = (double) ( loanAmount * (1+anualInterestRate/12));
            xponent = (double) (numberOfYears * 12);
            totalPay = (double) Math.pow(base, exponent); 
    
            // consider setting other fields with your parameters if they'll be 
            // needed elsewhere
        }