您可以检查是否priceField
包含字符串使用此:
JTextField priceField;
int price;
try {
// Check whether priceField.getText()'s length equals 0
if(priceField.getText().getLength()==0) {
throw new Exception();
}
// If not, check if it is a number and if so set price
price = Integer.parseInt(priceField.getText());
} catch(Exception e) {
// Either priceField's value's length equals 0 or
// priceField's value is not a number
// Output error, reset priceField and break the code
System.err.println("Price error, is the field a number and not empty?");
priceField.setText("");
break;
}
当if语句为真(如果priceField.getText()
长度为0)抛出异常,这将触发catch-block,发出错误,重置priceField
和break
的代码。
如果if语句虽然为假(如果priceField.getText()
的长度大于或小于0),它将检查priceField.getText()
是否是一个数字,如果是,则将price
设置为该值。如果它不是一个数字,则抛出一个NumberFormatException异常,这将触发catch-block等。
让我知道它是否有效。
编码愉快:) -Charlie
如果你想在Java虚拟机的正常运行期间抛出你的异常
这是如此丑陋... – slnowak 2014-11-01 19:37:35