使用带有double的switch语句时,操作数堆栈上的类型错误



以下程序编译时没有任何错误,但当我运行它时,我会得到java.lang.VerifyError

public class Main {
public static void main(String[] args) {
double d = 1;
switch (d) {
case 0.0: System.out.println("The value is zero");
case 1.0: System.out.println("The value isn't zero");
default: System.out.println("It's something else");
}
}
}

以下是完整的错误:

Exception Details:
Location:
Main.main([Ljava/lang/String;)V @3: tableswitch
Reason:
Type double_2nd (current frame, stack[1]) is not assignable to integer
Current Frame:
bci: @3
flags: { }
locals: { '[Ljava/lang/String;', double, double_2nd }
stack: { double, double_2nd }
Bytecode:
0000000: 0f48 27aa 0000 0025 0000 0000 0000 0001
0000010: 0000 0015 0000 001d b200 1012 16b6 0018
0000020: b200 1012 1eb6 0018 b200 1012 20b6 0018
0000030: b1
Stackmap Table:
append_frame(@24,Double)
same_frame(@32)
same_frame(@40)

这是否意味着switch语句根本不能在double上使用?当我尝试相同的代码,但使用int而不是double时,它可以正常工作。(在Windows 10 64位上使用VSCode 1.6.4中的Java 17(

问题出现在计算机中的双重表示中。浮点对开关来说不是很好。例如,即使这样,在Java中也不起作用:if(0.1 + 0.2 == 0.3)

如果你真的需要比较它们,你可以使用threshold comparison method。你在哪里做这样的事情:

double epsilon = 0.000000000000001d;
if(Math.abs(d1 - 0.0) < epsilon) {
System.out.println("The value is zero");
}
else if(Math.abs(d1 - 1.0) < epsilon) {
System.out.println("The value isn't zero");
}
else {
System.out.println("It's something else");
}

如果你不喜欢这个解决方案,你可以试着看看https://www.baeldung.com/java-comparing-doubles还有更多的解决方案。

最新更新