[英]giving a null value to a int type variable
我是 Java 新手,我已经搜索了 2 天如何实现这一点,但仍然没有弄清楚。 在我的 if 语句中,我需要确保如果用户只按 Enter 键而不输入值,则消息将提示重新输入,如果用户输入的值小于 1。下面是我的代码片段。 我已经阅读了 int cant except null,并且我尝试了 Integer ,但是我的代码不会运行
int numberOfCars = -1
while (numberOfCars == null || numberOfCars < 1)
{
numberOfCars = (JOptionPane.showInputDialog("Enter number of cars."));
if(numberOfCars == null || numberOfCars < 1)
{
JOptionPane.showMessageDialog(null, "Please enter a value.");
}
}
int numberOfCars = -1;
do {
String answer = JOptionPane.showInputDialog("Enter number of cars.");
if (answer != null && answer.matches("-?[0-9]+")) {
numberOfCars = Integer.parseInt(answer);
if (numberOfCars < 1) {
JOptionPane.showMessageDialog(null, "Value must be larger than 1.");
}
} else {
JOptionPane.showMessageDialog(null, "Value not a number.");
}
} while (numberOfCars < 1);
这会进行验证( matches
),否则parseInt
会抛出NumberFormatException
。
正则表达式String.matches(String)
.matches("-?[0-9]+")
这与模式匹配:
-?
= 减号,可选 ( ?
)[0-9]+
= 来自[ ... ]
一个字符,其中 0-9 是范围、数字以及一次或多次 ( +
)有关正则表达式的信息,另请参阅模式。
Integer.parseInt(string)
给出从字符串中获取的int
值。 就像除以零一样,这会引发错误,即 NumberFormatException。
此处适合使用 do-while 循环(很少适用)。 正常的 while 循环也可以。
JOptionPane.showInputDialog()
将返回一个String
。 当您尝试使用Integer.parseInt()
将其解析为int
时,您可以使用try-catch
语句来检查输入值是否正确。 这将适用于您的所有情况。
所以这可以工作:
int numberOfCars = -1;
while(numberOfCars < 1){
try{
numberOfCars = JOptionPane.showInputDialog("Enter number of cars.");
if(numberOfCars < 1){
JOptionPane.showMessageDialog(null, "Please enter a value.");
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please enter numeric value.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.