如下所示,我必须在计算执行之前在java中编写一个方法。我将检查该字符串是否仅包含数字,但如果我要输入浮点值,则不会验证它。
请为我建议正确的源代码。
if (Purchase_Paid.getText().matches("[0-9]+")) {
Global_Total = Float.parseFloat(Purchase_Amount.getText());
Globle_paidAmount = Float.parseFloat(Purchase_Paid.getText());
GlobleOutStandingAmount = (Global_Total - Globle_paidAmount);
Purchase_Outstanding.setText(String.valueOf(GlobleOutStandingAmount));
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Validation");
alert.setHeaderText(null);
alert.setContentText("Please enter only numbers in Paid fields");
alert.showAndWait();
}
答案 0 :(得分:0)
检查字符串是否为数字
if (Purchase_Paid.getText().matches("^[-+]?\\d+(\\.\\d+)?$")){
}
答案 1 :(得分:0)
正则表达式[0-9]+
仅匹配文本中的数字。如果您也想允许浮点数,请使用以下正则表达式
[+-]?([0-9]*[.])?[0-9]+
if (Purchase_Paid.getText().matches("[+-]?([0-9]*[.])?[0-9]+")) {
//Take Necessary action
}