简体   繁体   English

在Java中的另一个类中返回类构造函数字符串

[英]returning a class constructor string in another class in java

I have a class loan which has a constructor that set a string totalpaymentamt 我有一个类贷款,它的构造函数设置了一个字符串totalpaymentamt

I also have another class loan test which has the main method and am using it to output the string 我也有另一个类贷款测试,它具有main方法,并且正在使用它来输出字符串

I have done 我已经做好了

public class Loan {
    public Loan() {
        String totalpaymentamt = "\t toString() results" + this.toString(this.getDuration(),
            this.getInterestRate(),
            this.gettotalAmount()) + "  \n \t getNumberOfYears() results:" + this.getDuration() + " getInterestRate() results:" + this.getInterestRate() + "  getTotalAmount() results:" + this.gettotalAmount() + " getMonthlyPayment:" + this.getMonthlyPayment(this.getDuration(),
            this.getInterestRate(),
            this.gettotalAmount());
    }
}

The other class is 另一类是

public Loan(int duration, double interestRate, double totalAmount) {
     this.totalpaymentamt = "\t toString() results" + this.toString(duration, interestRate, totalAmount)

     + "  \n \t getNumberOfYears() results:" + duration
         + " getInterestRate() results:" + interestRate + "  getTotalAmount() results:" + totalAmount + " getMonthlyPayment:" + this.getMonthlyPayment(duration, interestRate, totalAmount);

}

This doesnt return anything. 这不返回任何东西。 I understand a constructor has no return statement, How can i return the results o the loan constructor to the Testloan class main method 我了解构造函数没有return语句,我如何将结果返回给Testloan类main方法的贷款构造函数

A constructor doesn't return anything. 构造函数不返回任何东西。

Also, In your TestLoan class, you're extending the Loan class, which you don't need to do. 另外,在您的TestLoan类中,您正在扩展Loan类,而您不需要这样做。

If you change the loan class constructor to something like this: 如果将贷款类构造函数更改为以下形式:

public class Loan {
    private String totalpaymentamt;

    public Loan() {

        this.totalpaymentamt = "\t toString() results"
                + this.toString(this.getDuration(),
                        this.getInterestRate(),
                        this.gettotalAmount())
                + "  \n \t getNumberOfYears() results:"
                + this.getDuration()
                + " getInterestRate() results:"
                + this.getInterestRate()
                + "  getTotalAmount() results:"
                + this.gettotalAmount()
                + " getMonthlyPayment:"
                + this.getMonthlyPayment(this.getDuration(),
                        this.getInterestRate(),
                        this.gettotalAmount());

    }


    public String getTotalPaymentAmount() {
        return this.totalpaymentamt;
    }
}

And then, in TestLoan, you can do: 然后,在TestLoan中,您可以执行以下操作:

Loan loan = new Loan();
System.out.println("First Loan \n " + loan.getTotalPaymentAmount());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM