在java中的另一个类中返回类构造函数字符串
我有一个类贷款,它有一个设置字符串totalpaymentamt的构造函数 我还有另一个类loan测试,它有main方法,我用它来输出字符串 我已经做了在java中的另一个类中返回类构造函数字符串,java,Java,我有一个类贷款,它有一个设置字符串totalpaymentamt的构造函数 我还有另一个类loan测试,它有main方法,我用它来输出字符串 我已经做了 public class Loan { public Loan() { String totalpaymentamt = "\t toString() results" + this.toString(this.getDuration(), this.getInterestRate(),
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语句,如何将loan构造函数的结果返回给Testloan类main方法构造函数不返回任何内容 另外,在TestLoan类中,您正在扩展Loan类,这是您不需要做的 如果将贷款类构造函数更改为以下内容:
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());
在类中有一个正式的toString方法并调用它,您需要重写对象类的toString()方法以使TestLoan主方法工作。您可以始终使用getter()方法并将字符串设置为全局私有字符串。我不确定这是否是最好的选择。@MichaelPickett它不一定需要是私有变量。getter可以直接返回该字符串。还有一件事,比如您创建自己的自定义
toString()
,从中返回string
,因为您没有覆盖默认的toString方法,请使用StringBuffer/Builder
。请检查toString()的正确用法。
一个简单的谷歌搜索可以解决这个问题。对不起,我必须插入另一个构造函数接受参数