[英]giving a null value to a int type variable
I am new to Java and I have been searching for 2 days how to accomplish this and still have not figured it out.我是 Java 新手,我已经搜索了 2 天如何实现这一点,但仍然没有弄清楚。 In my if statement I need to ensure that if a user just presses enter with out entering a value a message will prompt for re entry, also if the user enters a value less than 1. Below is a snip of my code.
在我的 if 语句中,我需要确保如果用户只按 Enter 键而不输入值,则消息将提示重新输入,如果用户输入的值小于 1。下面是我的代码片段。 I have read the int cant except null, and I have tried Integer , BUT my code wont run with that
我已经阅读了 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);
This does a validation ( matches
) as otherwise parseInt
would throw a NumberFormatException
.这会进行验证(
matches
),否则parseInt
会抛出NumberFormatException
。
Regular expression String.matches(String)
正则表达式
String.matches(String)
.matches("-?[0-9]+")
This matches the pattern:这与模式匹配:
-?
= a minus, optionally ( ?
) ?
)[0-9]+
= a character from [ ... ]
, where 0-9 is range, the digits, and that one or more times ( +
) [0-9]+
= 来自[ ... ]
一个字符,其中 0-9 是范围、数字以及一次或多次 ( +
) See also Pattern for info on regex.有关正则表达式的信息,另请参阅模式。
Integer.parseInt(string)
Gives an int
value taken from the string.给出从字符串中获取的
int
值。 Like division by zero this can raise an error, a NumberFormatException.就像除以零一样,这会引发错误,即 NumberFormatException。
Here a do-while loop would fit (it rarely does).此处适合使用 do-while 循环(很少适用)。 A normal while loop would be fine too.
正常的 while 循环也可以。
the JOptionPane.showInputDialog()
will return you a String
. JOptionPane.showInputDialog()
将返回一个String
。 You can use a try-catch
statement to check wether the input value is correct when you try to parse it to int
using Integer.parseInt()
.当您尝试使用
Integer.parseInt()
将其解析为int
时,您可以使用try-catch
语句来检查输入值是否正确。 This will work for all of your cases.这将适用于您的所有情况。
So this could work:所以这可以工作:
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.