我正在使用GUI处理java程序,每当我尝试添加文本字段中的值并且缺少一个时它遇到问题它不起作用我得到一个错误但是如果所有这些都可用我得到了正确的答案,如何在没有所有价值的情况下添加?
JButton btnCheckOut = new JButton("CHECK OUT");
btnCheckOut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double apples, strawberries, watermelon, tomatoe, carrot, beef, lamb, payment;
apples = Double.parseDouble(textField.getText());
strawberries = Double.parseDouble(textField_1.getText());
watermelon = Double.parseDouble(textField_2.getText());
tomatoe = Double.parseDouble(textField_3.getText());
carrot = Double.parseDouble(textField_4.getText());
beef = Double.parseDouble(textField_5.getText());
lamb = Double.parseDouble(textField_6.getText());
payment = (apples*8)+(strawberries*10)+(watermelon*14)+
(tomatoe*5)+(carrot*6)+(beef*25)+(lamb*20);
DecimalFormat df = new DecimalFormat("###.##");
textField_7.setText(String.valueOf(df.format(payment)));
}
});
答案 0 :(得分:0)
在进行数学运算之前,创建一个IF
语句,如果其各自的TextField为空,则将变量设置为zero
。
if(textfield.getText().isEmpty())
{
apples = 0;
}
答案 1 :(得分:0)
制作textFields时,将文本初始化为0.赞。
Microsoft.Office.Interop.Outlook.Application app;
Microsoft.Office.Interop.Outlook.Items items;
Microsoft.Office.Interop.Outlook.Items draftItems;
Microsoft.Office.Interop.Outlook.NameSpace ns;
Microsoft.Office.Interop.Outlook.MAPIFolder inbox;
Microsoft.Office.Interop.Outlook.MAPIFolder drafts;
Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application();
app = application;
ns = application.Session;
drafts = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderDrafts);
inbox = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
items = inbox.Items;
draftItems = drafts.Items;
string test;
foreach (Object _obj in draftItems)
{
if (_obj is Microsoft.Office.Interop.Outlook.MailItem)
{
Microsoft.Office.Interop.Outlook.MailItem blah = ((Microsoft.Office.Interop.Outlook.MailItem)_obj);
blah.Send();
}
}
foreach (Object _obj in items)
{
if (_obj is Microsoft.Office.Interop.Outlook.MailItem)
{
Microsoft.Office.Interop.Outlook.MailItem blah = ((Microsoft.Office.Interop.Outlook.MailItem)_obj);
if (blah.UnRead)
{
test = blah.Subject.ToString();
test = blah.Body.ToString();
}
}
}
或者,您可以添加
JTextField textField_1 = new JTextField("0");
在尝试解析为double之前的每个文本字段。
答案 2 :(得分:0)
创建例如getDoubleValue,您在阅读时应用于所有项目。简单如下:
apples = getDoubleValue( textField.getText() );
...
...
然后
public double getDoubleValue( String txt ) {
double d = 0d;
try {
if( txt != null && !txt.isEmpty() ) {
d = Double.parseDouble( txt );
}
} catch(Exception ex) {}
return d;
}
(这也会关注“脏输入”,如果文本字段不包含数字,它将在解析期间将其设置为零。)