我正在使用TextPad为我的班级制作旅行费用计算器。该程序应该通过GUI上的文本字段从用户获取输入,然后进行以下计算:(miles*gaspergallon)+oilchange
。我能够编译代码但是我收到以下错误:
线程“main”中的异常java.lang.numberformatexception:为空 字符串。
这是我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GasCalc extends JFrame {
JTextField jtfMiles, jtfCostPerGallon, jtfOilChangeCost, jtfInfo1, jtfInfo2, jtfInfo3;
Double total = 0.00;
Double miles = 0.00;
Double costpergallon = 0.00;
Double oilchange = 0.00;
String display = "";
TextHandler handler = null;
public GasCalc(){
super("Travelor's Gasoline Calculator");
Container container = getContentPane();
container.setLayout(new FlowLayout());
jtfInfo1 = new JTextField("Please Enter the number of miles you will travel.",40);
jtfInfo1.setEditable(false);
jtfMiles = new JTextField(10);
jtfInfo2 = new JTextField("Please Enter the cost per gallon.",30);
jtfInfo2.setEditable(false);
jtfCostPerGallon = new JTextField(10);
jtfInfo3 = new JTextField("Please Enter the cost of oil change, if applicable.",45);
jtfInfo3.setEditable(false);
jtfOilChangeCost = new JTextField("0.00",10);
container.add(jtfInfo1);
container.add(jtfMiles);
container.add(jtfInfo2);
container.add(jtfCostPerGallon);
container.add(jtfInfo3);
container.add(jtfOilChangeCost);
handler = new TextHandler();
jtfInfo1.addActionListener(handler);
jtfMiles.addActionListener(handler);
jtfInfo2.addActionListener(handler);
jtfCostPerGallon.addActionListener(handler);
jtfInfo3.addActionListener(handler);
jtfOilChangeCost.addActionListener(handler);
miles = Double.parseDouble(jtfMiles.getText());
costpergallon = Double.parseDouble(jtfCostPerGallon.getText());
oilchange = Double.parseDouble(jtfOilChangeCost.getText());
total = (miles*costpergallon)+ oilchange;
setSize(500,500);
setVisible(true);
}
private class TextHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == total){
display = "Your total is: " + e.getActionCommand();
} else if (e.getSource() == jtfInfo1){
display = "Your total is not: " + e.getActionCommand();
}
JOptionPane.showMessageDialog(null,display);
}
}
public static void main(String args[]){
GasCalc test = new GasCalc();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:1)
它将是,因为您只需从文本字段中获取值并解析为Double而不进行检查。
第一次,当程序启动时,它执行总计。但每个领域都是空白的。空白无法解析为双倍。所以,它显示错误。
所以,我建议像这样使用:
if(jtfMiles.getText().isEmpty()){
JOptionPane.showMessageDialog("Error Found in execution!!!","Miles field should not empty.");
} else if (jtfCostPerGallon.getText().isEmpty()){
JOptionPane.showMessageDialog("Error Found in execution!!!","Cost per Gallon field should not empty.");
} else if (jtfOilChangeCost.getText().isEmpty()){
JOptionPane.showMessageDialog("Error Found in execution!!!","Oil change cost field should not empty.");
} else {
miles = Double.parseDouble(jtfMiles.getText());
costpergallon = Double.parseDouble(jtfCostPerGallon.getText());
oilchange = Double.parseDouble(jtfOilChangeCost.getText());
total = (miles*costpergallon)+ oilchange;
}