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

问题描述 投票:0回答:1

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

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());

        }
java
1个回答
0
投票

Integer.parseInt()包装在try块中,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");
}
© www.soinside.com 2019 - 2024. All rights reserved.