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