我正在写一个ATM代码,但我面临一个简单的问题(我希望),当我点击存款按钮时,会弹出一个新窗口,上面有按钮(0到9),用户输入他希望的金额,然后通过按提交,标签中的文本被解析为双倍然后返回到存款方法,这增加了余额(双倍)返回的金额。问题是当用户打开存款弹出然后通过单击X按钮关闭它时,字符串返回一个空字符,这给我一个错误(NumberFormatException:空字符串),因为你不能解析null到double。
我尝试了一个if语句,如果字符串为null,让它为“0”,但事务历史(字符串数组)存储“存款:0 $”,这不是真的,因为他没有点击提交按钮(也是不合逻辑的)。所以我需要知道如果字符串为null,可能就像终止操作并返回上一个场景而不返回任何值到存款方法。
这是返回的代码
String value = labelNum.getText();
if(value == null || value.isEmpty()) { value = ""; }
return Double.valueOf(value);
这是它返回的方法:
public void setDeposit(double deposit) { balance = balance + deposit; }
与@FailingCoder一起使用,您可以在if
语句和setDeposit()
函数中添加一些防御性编码,以便使代码检查deposit = 0
语句。例如,
if(value != null && !value.isEmpty()){
return Double.valueOf(value);
}
else
return 0.0;
并在setDeposit()
功能
public void setDeposit(double deposit)
{
if(deposit > 0) //to avoid negative entries else != should also work
balance = balance + deposit;
}
假设你有正确的正则表达式过滤字母减法符号,我会推荐一些东西,但是你的措辞使它听起来像这应该不是一个问题,因为只有数字1-9我编码了所以你知道发生了什么然后你没有尝试返回null或0.0取决于你如何编码你可以绑定你的帐户余额和标签,然后你不必“刷新”标签,我讨厌,但这只是让你可以了解解决这个问题的其他方法
public class Main extends Application {
private Label balanceLabel;
private double accountBalance = 0.0;
@Override
public void start(Stage primaryStage) throws Exception {
balanceLabel = new Label();
setNewAccountBalanceLabel();
Button depositButton = new Button("Deposit Money");
depositButton.setOnAction(event -> depositAction());
VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
vBox.getChildren().addAll(balanceLabel, depositButton);
Stage stage = new Stage();
stage.setScene(new Scene(vBox));
stage.show();
}
private void setNewAccountBalanceLabel(){
balanceLabel.setText("Balance:"+accountBalance);
}
private void depositAction(){
getDepositAmount();
setNewAccountBalanceLabel();
}
private void getDepositAmount(){
Stage stage = new Stage();
VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
Label depositAmountLabel = new Label("0.00");
TextField depositAmountTextField = new TextField();
depositAmountTextField.setPromptText("Only Numbers");
depositAmountTextField.setOnKeyReleased(keyEvent-> depositAmountLabel.setText(depositAmountTextField.getText()));
Button submitButton = new Button("Submit");
submitButton.setOnMouseClicked(event -> {
double depositAmount = Double.parseDouble(depositAmountLabel.getText());
accountBalance = accountBalance + depositAmount;
stage.close();
});
vBox.getChildren().addAll(depositAmountLabel, depositAmountTextField, submitButton);
stage.setScene(new Scene(vBox));
stage.showAndWait();
}
public static void main(String[] args) { launch(args); }
}