ComboBox和计算的麻烦

时间:2013-04-12 17:24:53

标签: java user-interface combobox

我正在尝试使用一种方法来计算行程的持续时间,使用:

  private void updateTripDurationText()
{


    String speed = (String)avgspeedBox.getSelectedItem();
    String dist = (String)distanceText.getText();

    double s = Double.parseDouble(speed);
    double d = Double.parseDouble(dist);
    double durationTime = d/s;
    String dTime = String.format("1%.1f", Double.toString(durationTime));
    durationText.setText(dTime);

   }

虽然我可以运行该程序,但我收到一个涉及空字符串的错误。该程序有3个组合框。在那里你选择你的A和B位置然后它会调出距离。我希望第三个组合框(速度)计算持续时间作为距离/速度然后将其放入文本框。我哪里错了?

这是动作监听器:

private class ComboBoxListener implements ActionListener
{


  public void actionPerformed(ActionEvent e)
  {

        setCities(destinationBox.getSelectedIndex(),originBox.getSelectedIndex());
     updateDistanceText();
        updateTripDurationText();

   }

 }

将其分成不同的事件处理程序后,我遇到了计算错误的问题。持续时间的计算返回非常大的值。

2 个答案:

答案 0 :(得分:3)

尝试

String.valueOf(Primitive/Object Reference) 

而不是toString方法,以便在基元或对象导致NullPointerException值的情况下不会抛出任何NULL。此外,ComboBoxListBox使用ItemListener并覆盖其方法itemStateChanged()

答案 1 :(得分:1)

在使用Double.parseDouble解析它们之前,检查speeddist是否为空可能是个好主意。但是如果有人进入“20.2英里”的话,那该怎么办?它不是空字符串,但仍会抛出NumberFormatException。

if ((speed.length() > 0) && (dist.length() > 0)) {
  String speed = (String)avgspeedBox.getSelectedItem();
  // rest of your code...
}

尝试捕获异常,如果被捕获,请让用户知道他们的输入是错误的。

try {
    if ((speed.length() > 0) && (dist.length() > 0)) {
      String speed = (String)avgspeedBox.getSelectedItem();
      // rest of your code...
    }
} catch (NumberFormatException nfe) {
  // show some kind of warning message
}
相关问题