我試圖在toString()
中打印字符串。如果我刪除了%.0f
和this.years
替代品,它會打印出正常,但如果包含它,則不會打印。我不知道爲什麼。我能想到的唯一原因可能是因爲年份是int
,而我的字符串格式只適用於doubles
?錯誤打印字符串使用%替換格式化爲%.0f
如何更改代碼以便我可以將%.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)
它的工作!這回答了這個問題,謝謝!我知道這可能只是錯誤的格式。再次感謝! –