【问题标题】:Error converting from String to int to Vaadin从 String 转换为 int 到 Vaadin 时出错
【发布时间】:2020-01-15 15:13:09
【问题描述】:

我正在尝试在 Vaadin 中将 String 转换为 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: ""'

【问题讨论】:

  • "" 插入Integer.parseInt 函数时的预期结果是什么?不确定您想要做什么,但您正在尝试解析一个空字符串,这会导致 NumberFormatException
  • 在消息的末尾有一个java.lang.NumberFormatException: For input string: "",这意味着它不能将空字符串解析为int。这里name = new TextField(); 你创建了初始值为空的TextField,并在下一行中使用它作为输入,你不能期望那里有一个值。
  • 您似乎希望这个int num = Integer.parseInt(String.valueOf(name.getValue()));event->{} 的内部,所以您在名称中输入值,按下按钮,然后在问候语中得到 num*500,对吗?跨度>
  • 顺便说一句。打电话给String.valueOf(name.getValue()) 毫无意义。 name.getValue() 已经返回一个字符串,所以从它解析字符串什么都不做。
  • 除了按照 yuri 说的做之外,你还必须实现异常处理,也就是在 Integer.parseInt(..) 行周围的 try-catch,它应该在按钮点击事件中。

标签: java spring string int vaadin


【解决方案1】:

正如cmets中所说:

1) 仅在按钮的 clicklistener 内解析输入值,而不是直接在视图的构造函数内解析(此时,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 - 绑定 textField 时,您可以添加 StringToIntegerConverter。这会有点复杂,我不会仅仅为了这个而走那条路。

【讨论】:

    【解决方案2】:

    正如 cmets 中的其他人所说,一种解决方案是捕获异常:

    try {
      num = Integer.parseInt(name.getValue());
    } catch (NumberFormatException nfe) {
      num = 1; // your default value
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 2023-01-08
      • 2015-05-11
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多