Java netbeans - 如果 jtextfield 值为空,如何将 jtextfield 值赋给零
Java netbeans - how assign jtextfield value to zero if jtextfield value is empty
double B=Double.parseDouble(emp_txt2.getText());
double C=Double.parseDouble(nopay_txt3.getText());
double E=Double.parseDouble(wop_txt4.getText());
double F=Double.parseDouble(wop_txt5.getText());
double f =B+C+E+F;
String p = String.format("%.2f",f);
lb1_total3.setText(p);
我想在 jtextfield 为空时将双 B、C、E、F 值分配为零。
您可以使用此方法代替 Double.parseDouble。
public static double tryParsDouble(String s, double defaultValue) {
if (s == null) return defaultValue;
try {
return Double.parseDouble(s);
} catch (NumberFormatException x) {
return defaultValue;
}
}
然后到:
double F = tryParsDouble(wop_txt5.getText(), 0.0);
尝试在 emp_text2
文本字段和代码 returns 中分别输入以下值:
""
, " "
, "1"
, "1.1"
, "-1.1"
, "1.0 "
returns 0.0
, 0.0
, 1.0
, 1.1
, -1.1
, 1.0
.
如果输入 "1.1x"
会怎样?这会抛出 NumberFormatException
- 应用程序需要确定要做什么。
double value = getDoubleValue(emp_text2.getText());
...
private static double getDoubleValue(String input) {
double result = 0d;
if ((input == null) || input.trim().isEmpty()) {
return result;
}
try {
result = Double.parseDouble(input);
}
catch (NumberFormatException ex) {
// return result -or-
// rethrow the exception -or-
// whatever the application logic says
}
return result;
}
double B=Double.parseDouble(emp_txt2.getText());
double C=Double.parseDouble(nopay_txt3.getText());
double E=Double.parseDouble(wop_txt4.getText());
double F=Double.parseDouble(wop_txt5.getText());
double f =B+C+E+F;
String p = String.format("%.2f",f);
lb1_total3.setText(p);
我想在 jtextfield 为空时将双 B、C、E、F 值分配为零。
您可以使用此方法代替 Double.parseDouble。
public static double tryParsDouble(String s, double defaultValue) {
if (s == null) return defaultValue;
try {
return Double.parseDouble(s);
} catch (NumberFormatException x) {
return defaultValue;
}
}
然后到:
double F = tryParsDouble(wop_txt5.getText(), 0.0);
尝试在 emp_text2
文本字段和代码 returns 中分别输入以下值:
""
, " "
, "1"
, "1.1"
, "-1.1"
, "1.0 "
returns 0.0
, 0.0
, 1.0
, 1.1
, -1.1
, 1.0
.
如果输入 "1.1x"
会怎样?这会抛出 NumberFormatException
- 应用程序需要确定要做什么。
double value = getDoubleValue(emp_text2.getText());
...
private static double getDoubleValue(String input) {
double result = 0d;
if ((input == null) || input.trim().isEmpty()) {
return result;
}
try {
result = Double.parseDouble(input);
}
catch (NumberFormatException ex) {
// return result -or-
// rethrow the exception -or-
// whatever the application logic says
}
return result;
}