目前,如果该字段为空,我的错误异常处理将返回错误-我如何扩展它以包括不是正整数的所有字符?
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
块中,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");
}