问题
Here is a part of my code I'm having trouble with:
===Class Overload===
public class Overload
{
public void testOverLoadeds()
{
System.out.printf("Square of integer 7 is %d\n",square(7));
System.out.printf("Square of double 7.5 is %d\n",square(7.5));
}//..end testOverloadeds
public int square(int intValue)
{
System.out. printf("\nCalled square with int argument: %d\n",intValue);
return intValue * intValue;
}//..end square int
public double square(double doubleValue)
{
System.out.printf("\nCalled square with double argument: %d\n", doubleValue);
return doubleValue * doubleValue;
}//..end square double
}//..end class overload
===Main===
public static void main(String[] args) {
Overload methodOverload = new Overload();
methodOverload.testOverLoadeds(); }
It compiles with no error, however when I try to run it the output is:
Called square with int argument: 7
Square of integer 7 is 49Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999) at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2709) at java.util.Formatter$FormatSpecifier.print(Formatter.java:2661) at java.util.Formatter.format(Formatter.java:2433) at java.io.PrintStream.format(PrintStream.java:920) at java.io.PrintStream.printf(PrintStream.java:821) at methodoverload.Overload.square(Overload.java:19) at methodoverload.Overload.testOverLoadeds(Overload.java:8) at methodoverload.Main.main(Main.java:9) Called square with double argument:Java Result: 1
What am I doing wrong?
I'm on Ubuntu 10.10, Netbeans 6.9.
Thanks.
回答1:
The format specifier for double values is f, not d. So this line should be:
System.out.printf("\nCalled square with double argument: %f\n", doubleValue);
More details about the format specifiers here.
回答2:
try this
public class Overload {
public void testOverLoadeds() {
System.out.printf("Square of integer 7 is %d\n", square(7));
System.out.printf("Square of double 7.5 is %.4f%n", square(7.5));
}// ..end testOverloadeds
public int square(int intValue) {
System.out.printf("\nCalled square with int argument: %d\n", intValue);
return intValue * intValue;
}// ..end square int
public double square(double doubleValue) {
System.out.printf("\nCalled square with double argument: %.4f%n",doubleValue);
return doubleValue * doubleValue;
}// ..end square double
// ..end class overload
public static void main(String[] args) {
Overload methodOverload = new Overload();
methodOverload.testOverLoadeds();
}
}
You need to change the double formatter "%d\n"
来源:https://stackoverflow.com/questions/4568345/java-methodoverloading-error-with-double-values