繁体   English   中英

如果我正在解析的字符串为空,如何从Double.parseDouble调用中返回零?

[英]How can I return zero from this Double.parseDouble call if the string I'm parsing is empty?

这是我的代码:

private class CalcButtonListener implements ActionListener //Action from listner

        {public void actionPerformed(ActionEvent c)

              {double total = 0;
               double hours = Double.parseDouble(thours.getText());
               double pcharge = Double.parseDouble(tparts.getText());
               if(coil.isSelected()){total += 26;}
               if(clube.isSelected()){total += 18;}
               if(cradiator.isSelected()){total += 30;}
               if(ctransmission.isSelected()){total += 80;}
               if(cinspection.isSelected()){total += 15;}
               if(cmuffler.isSelected()){total += 100;}
               if(ctire.isSelected()){total += 20;}
               else{total = total;}
               total += (pcharge + (hours*20));
               JOptionPane.showMessageDialog(null,"Total Charges : $" + total);}}

“ thours”和“ tparts”是用户输入数字的字段,但是由于我使用该值进行计算,因此我相信它会返回错误,因为该行没有值。 在这种情况下,如何使该代码返回零?

我认为您的意思是将变量值设置为0 如果没有,请澄清。

使用三元表达式来执行此操作。 例如,对于hours ,请使用:

double hours = thours.getText().isEmpty() ? 0 : Double.parseDouble(thours.getText());

如果thours.getText().isEmpty()为true,则hours将设置为0 否则, hours将设置为Double.parseDouble(thours.getText())

double hours;
if (!"".equals(thours.getText()))}{
    try {
        hours = Double.parseDouble(thours.getText());
    } catch (NUmberFormatException ex){
        JOptionPane.showMessageDilaog(null, "Please enter a valid number");
    }
}

代码检查文本是否包含任何字符,如果输入不是数字,则检查try / catch以捕获任何数字格式异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM