2016-09-17 69 views
-1

另一个类返回一个类的构造函数的字符串我有一个类贷款,其具有设置字符串totalpaymentamt在Java

我也有具有的主要方法和其他类贷款的测试构造现在用它来输出串

我已经做了

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

另一类是

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

} 

这不会返回任何东西。我明白了一个构造函数没有return语句,我该怎么Ø贷款构造函数将结果返回给Testloan类主要方法

+2

在类的正式toString方法和调用 – Li357

+0

您需要重写Object类的toString()方法以使该TestLoan主方法可以工作 –

+0

始终可以使用getter()方法并使您的String成为全局私有字符串。林不知道这是否是最好的选择。 –

回答

4

一个构造函数不返回任何东西。

此外,在您的TestLoan类中,您正在扩展贷款类,您不需要这样做。

如果改变贷款类的构造函数是这样的:

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

,然后在TestLoan,你可以这样做:

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

对不起,但我已经orgot插入,有另一个构造函数参数 –