我正在尝试在中打印字符串toString()
。如果删除%.0f
和,它可以很好地打印this.years
,但是如果包含它和它,则不能打印。我不知道为什么。我能想到的唯一原因也许是因为years是an int
,而我的字符串格式仅适用于doubles
?
如何更改代码,这样我可以替代%.0f
用this.years
?
// instance members
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
// public instance method
public MyLoan(double amt, double rt, int yrs) {
this.amountBorrowed = amt;
this.yearlyRate = rt;
this.years = yrs;
this.n = yrs * 12;
public String toString() {
String temp1 = String.format("Loan: $%.2f at %.2f for %.0f years.", this.amountBorrowed, this.yearlyRate, this.years);
return temp1;
尝试打印时收到的错误是:
Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302) at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2806) at java.util.Formatter$FormatSpecifier.print(Formatter.java:2753) at java.util.Formatter.format(Formatter.java:2520) at java.util.Formatter.format(Formatter.java:2455) at java.lang.String.format(String.java:2940) at hw2.MyLoan.toString(MyLoan.java:61) at hw2.MyLoan.main(MyLoan.java:101)
使用“%d”而不是“%.0f”来格式化“ int”。
有关格式化的更多信息,请参见此处http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句