强制转换double时的类转换异常

Tsa*_*sar -2 java double casting joptionpane

我尝试运行以下代码.它编译,但抛出ClassCastException.如果有人能帮助我找出原因,我会很高兴的.

double costprice = 0;
Object[] possibilities = null;
costprice = (double) JOptionPane.showInputDialog(
                    alphaPOS,
                    "Cost Price:",
                    "Enter Values",
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    possibilities,
                    "");
Run Code Online (Sandbox Code Playgroud)

Sam*_*s33 6

JOptionPane.showInputDialog()返回一个Object(@SeleenVirtuose的信用),它不能转换为a double,用于Double.parseDouble()将String解析为double.

costprice = Double.parseDouble(JOptionPane.showInputDialog(
                alphaPOS,
                "Cost Price:",
                "Enter Values",
                JOptionPane.PLAIN_MESSAGE,
                null,
                possibilities,
                ""));
Run Code Online (Sandbox Code Playgroud)

此外,你可以在一条线上完成所有这些

当您声明double变量然后立即设置时,您可以声明它并在一行中分配新值

double costprice = Double.parseDouble(JOptionPane.showInputDialog(
            alphaPOS,
            "Cost Price:",
            "Enter Values",
            JOptionPane.PLAIN_MESSAGE,
            null,
            possibilities,
            ""));
Run Code Online (Sandbox Code Playgroud)

此外,由于possibilities变量为null,只需null作为参数传递(除非您已将变量更改为其他位置)

double costprice = Double.parseDouble(JOptionPane.showInputDialog(
            alphaPOS,
            "Cost Price:",
            "Enter Values",
            JOptionPane.PLAIN_MESSAGE,
            null,
            nulll,
            ""));
Run Code Online (Sandbox Code Playgroud)