java - 我需要关于如何终止操作的意见(将空字符串解析为双精度)
问题描述
我正在编写一个 ATM 代码,但我面临一个简单的问题(我希望如此),即当我单击存款按钮时,会弹出一个带有按钮的新窗口(0 到 9),用户输入这些按钮他希望的金额,然后按提交,标签中的文本被解析为加倍,然后返回到存款方法,该方法将余额(加倍)增加返回的金额。问题是当用户打开存款弹出窗口然后通过单击 X 按钮将其关闭时,该字符串返回一个空字符,这给了我一个错误(NumberFormatException:空字符串),因为您无法将空值解析为加倍。
我尝试了一个 if 语句来判断字符串是否为空,让它为“0”,但是交易历史记录(字符串数组)存储“存款:0$”,这是不正确的,因为他没有点击提交按钮(这也是不合逻辑的)。所以我需要知道如果字符串为空,可能会终止操作并返回上一个场景而不向存款方法返回任何值。
这是返回代码
String value = labelNum.getText();
if(value == null || value.isEmpty()) { value = ""; }
return Double.valueOf(value);
这是它返回的方法:
public void setDeposit(double deposit) { 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); }
}
推荐阅读
- ios - QT Creator iOS 错误:Xcode 设备窗口中的设置可能不正确
- c# - 将 DataGrid 行绑定到 ViewModel 中的方法
- javascript - 草坪缓冲区传单geojson ajax
- javascript - 使用 php Web 应用程序进行 Firebase 会话管理
- wordpress - WordPress 管理页面未显示
- javascript - gatsbyjs中如何编译非网页的js文件
- scala - Spark:ColumnType内Array中值的索引
- python - Python 2.7 - Outlook Win32com.client 无法从 .msg 获取发件人的实际电子邮件地址
- typescript - Ionic 4 + Angular 6 PWA 样式不起作用/损坏
- excel - VBA删除excel中的多行