try {
Character.isDigit(Integer.parseInt(txtWeight.getText()));
} catch (java.lang.NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Enter a number");
pnlStart.setSelectedIndex(2);
}
txtWeight是一个JTextField,用户可以输入自己的值。我需要检查用户输入的是否是使用try catch的整数,以便该程序进入时不会崩溃。使用try catch语句检查用户的条目是否是整数
UPDATE:
boolean s = false;
while (s == false) {
try {
Integer.parseInt(txtWeight.getText());
s = false;
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Enter a number!");
s =true;
}
}
什么是你的问题:您正在使用
if
声明,呼吁该boolean
方法在做什么?这段代码有问题吗? – 4castle嗯......我会这样做的任何有符号,无符号,整数或双数值的方式是使用[正则表达式](http://www.vogella.com/tutorials/JavaRegularExpressions/article.html)使用[** String.matches()**](https://www.tutorialspoint.com/java/java_string_matches.htm)方法:'if(s.matches(“ - ?\\ d +(\\。\ \ d +)?“)){//是的,它是数字。 }'。 – DevilsHnd