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

时间:2015-09-30 13:47:44

标签: java string-formatting

我正在尝试在toString()中打印字符串。如果我删除%.0fthis.years替换,它打印正常,但如果我包含它,则不打印。我不知道为什么。我能想到的唯一原因可能是因为多年是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)

1 个答案:

答案 0 :(得分:2)

使用'%d'而不是'%。0f'用于格式化' int'。

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