gpt4 book ai didi

java - 从 String 转换为 int 再转换为 Vaadin 时出错

转载 作者:行者123 更新时间:2023-12-01 19:31:07 43 4
gpt4 key购买 nike

我正在尝试将 Vaadin 中的字符串转换为 int。这是代码:

TextField name = new TextField();
int num;
num = Integer.parseInt(String.valueOf(name.getValue()));
Paragraph greeting = new Paragraph("");
Button button = new Button("Result", event -> {
greeting.setText(" " + num * 500);
});
add(name, button, greeting);

这是错误:

There was an exception while trying to navigate to '' with the exception message 'Error creating bean with name 'com.gmail.ilim.MainView': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.gmail.ilim.MainView]: Constructor threw exception; nested exception is java.lang.NumberFormatException: For input string: ""'

最佳答案

正如评论中所说:

1) 仅在按钮的点击监听器内解析输入值,而不是直接在 View 的构造函数内解析(此时,TextField 将始终具有空值)

2) 捕获 NumberFormatException。即使解决了第 1 点,用户也始终可以输入无法解析为 Integer

的非数字内容
TextField name = new TextField();
Paragraph greeting = new Paragraph("");
Button button = new Button("Result", event -> {
int num;
try {
num = Integer.parseInt(String.valueOf(name.getValue()));
} catch (NumberFormatException e) {
num = 0; // your default value
// you should also let the user know he didnt enter a valid number
Notification.show("Please enter a valid number");
}
greeting.setText(" " + num * 500);
});
add(name, button, greeting);

另一种可能性是直接使用IntegerField而不是TextField。这仅适用于 Vaadin 14.1.x

我想到的另一种可能性是使用 Binder - 绑定(bind)文本字段时,您可以添加一个 StringToIntegerConverter。这会有点复杂,我不会仅仅为了这个就走那条路。

关于java - 从 String 转换为 int 再转换为 Vaadin 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59754309/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com