Reputation: 1726
I am trying to print the string in toString()
. It prints fine if I remove the %.0f
and the this.years
substitute, but does not print if I include it. I am not sure why. The only reason I can think of is perhaps it is because years is an int
, and my string formatting only works with doubles
?
How can I change the code so that I can substitute the %.0f
with 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;
The error I receive when trying to print is:
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)
Upvotes: 2
Views: 2459
Reputation: 5741
Use '%d' instead of '%.0f' for formating 'int'.
For more about formatting see here http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
Upvotes: 2