gpt4 book ai didi

具有双值的 Java MethodOverloading 错误

转载 作者:行者123 更新时间:2023-11-29 09:23:34 25 4
gpt4 key购买 nike

这是我遇到问题的部分代码:

===类重载===

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(); }

它编译没有错误,但是当我尝试运行它时,输出是:

Called square with int argument: 7
Square of integer 7 is 49

Exception 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

我做错了什么?

我在 Ubuntu 10.10、Netbeans 6.9 上。

谢谢。

最佳答案

double 值的格式说明符是 f,而不是 d。所以这一行应该是:

 System.out.printf("\nCalled square with double argument: %f\n", doubleValue);

有关格式说明符的更多详细信息 here .

关于具有双值的 Java MethodOverloading 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4568345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com