使用 int 替代打印格式为 %.0f 的字符串时出错

Error printing string formatted with %.0f using an int substitute

我正在尝试打印 toString() 中的字符串。如果我删除 %.0fthis.years 替代,它打印正常,但如果我包含它则不会打印。我不确定为什么。我能想到的唯一原因可能是因为年份是 int,而我的字符串格式只适用于 doubles

如何更改代码,以便我可以用 this.years 替换 %.0f

// 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”而不是“%.0 f”来格式化 'int'。

有关格式的更多信息,请参见此处 http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html