-1

我正在构建的系统计算英尺到英寸,但是每当其中一个文本字段保持打开状态时,系统就无法运行(例如(??/12)+?)我想知道当文本字段为空时如何设置它number 默认设置为零。

package calcu;
import java.awt.event.ItemEvent;
import java.text.NumberFormat;
import java.awt.event.KeyEvent;
import javax.swing.JFormattedTextField.*;
import javax.swing.*;
import javax.swing.JFormattedTextField.*;

void carefull() {
    String sumthing = "";
    double feet = Double.parseDouble(jTextField1.getText());

    double inches = Double.parseDouble(jTextField2.getText());
    NumberFormat changer = NumberFormat.getNumberInstance();
    double tik = feet * 12;

    double tok = inches + tik;

    try {
        if (jTextField1.getText().trim().equals("")) {
            double ans = inches;
            sumthing = changer.format(ans);
        }
        if (jComboBox1.getSelectedItem().equals(" ")) {
            sumthing = changer.format(tok);
        }
    } catch (NumberFormatException e) {
        spum1.setText(sumthing);
    }
}  
4

2 回答 2

1

你应该像这样捕获NumberFormatException

double feet;
try {
    feet = Double.parseDouble(jTextField1.getText());
} catch (NumberFormatException e) {
    feet = 0;
}
double inches;
try {
    inches = Double.parseDouble(jTextField2.getText());
} catch (NumberFormatException e) {
    inches = 0;
}

这也会将非数字解释123kjh为 0。

于 2013-07-22T19:11:25.630 回答
1

你可以试试这个:

String stringFeet = jTextField1.getText();
double feet = stringFeet.isEmpty() ? 0d : Double.parseDouble(stringFeet);
于 2013-07-22T19:11:40.940 回答