gpt4 book ai didi

java - Java FX 输入字段的错误异常处理,确保该字段只接受正整数

转载 作者:行者123 更新时间:2023-12-01 18:25:36 25 4
gpt4 key购买 nike

目前,如果字段为空,我的错误异常处理会返回错误 - 如何扩展它以包含所有非正整数的字符?

Button hdButton=new Button();
hdButton.setText("Save");
hdButton.setOnAction(e ->
{
if(memoryField.getText().isEmpty())
{
dsdisplay2.setText("ERROR: You must enter a positive number in order to set the
memory\n");
}
else
{
s1.setHardDisk(Integer.parseInt(hardDisk.getText()));
dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());

}

最佳答案

Integer.parseInt() 封装在 try block 中,并catch NumberFormatException

try {
int size = Integer.parseInt(hardDisk.getText());
s1.setHardDisk(size);
dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());
} catch (NumberFormatException e) {
dsdisplay2.setText("ERROR: You must enter a positive number in order to set the memory\n");
}

这样,您就不需要在设置 s1.setHardDisk 之前验证输入,因为如果输入格式错误,Integer.parseInt 将引发异常。

关于java - Java FX 输入字段的错误异常处理,确保该字段只接受正整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60237421/

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