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

标签 java

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

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/

相关文章:

java - 为什么我不能以这种方式访问​​ Java 中的 protected 变量?

java - 在 JLabels 之间创建垂直空间未按预期进行

Java:消除具有相同数字的结果

Java 类未从 IIB 中的 javaclassloader 服务加载

java - 使用线程池和优先级队列的调度程序?

java - java代码颜色示例中>>和&运算符的含义是什么

java - Perl 从右到左替换

java - 特殊字符的正则表达式

java - Android OCR 超正方体 : using data from Pixa objects to display bounding boxes

java - 从 Java 1.4 连接到 SQL 2008