2015-09-30 63 views
2

我试图在toString()中打印字符串。如果我删除了%.0fthis.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)

回答