如何判断 Java 整数是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/646012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I tell if a Java integer is null?
提问by Jeremiah Burley
Greetings,
你好,
I'm trying to validate whether my integer is null. If it is, I need to prompt the user to enter a value. My background is Perl, so my first attempt looks like this:
我正在尝试验证我的整数是否为空。如果是,我需要提示用户输入一个值。我的背景是 Perl,所以我的第一次尝试是这样的:
int startIn = Integer.parseInt (startField.getText());
if (startIn) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
This does not work, since Java is expecting boolean logic.
这不起作用,因为 Java 需要布尔逻辑。
In Perl, I can use "exists" to check whether hash/array elements contain data with:
在 Perl 中,我可以使用“exists”来检查哈希/数组元素是否包含以下数据:
@items = ("one", "two", "three");
#@items = ();
if (exists($items[0])) {
print "Something in \@items.\n";
}
else {
print "Nothing in \@items!\n";
}
Is there a way to this in Java? Thank you for your help!
在 Java 中有没有办法做到这一点?感谢您的帮助!
Jeremiah
耶利米
P.S. Perl existsinfo.
PS Perl存在信息。
采纳答案by John Feminella
parseInt()
is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers
, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
parseInt()
如果解析无法成功完成,只会抛出异常。您可以改为使用Integers
,相应的对象类型,这使事情变得更清晰。所以你可能想要更接近的东西:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Bewareif you do decide to use parseInt()
! parseInt()
doesn't support good internationalization, so you have to jump through even more hoops:
如果您决定使用,请当心parseInt()
!parseInt()
不支持良好的国际化,所以你必须跳过更多的箍:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
回答by Thomas
int
s are value types; they can never be null
. Instead, if the parsing failed, parseInt
will throw a NumberFormatException
that you need to catch.
int
s 是值类型;他们永远不可能null
。相反,如果解析失败,parseInt
将抛出一个NumberFormatException
你需要捕捉的。
回答by John Topley
Try this:
尝试这个:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
回答by Peter Lawrey
I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.
我认为您不能在 Perl 中对整数使用“exists”,只能在集合上使用。你能举一个例子说明你在 Perl 中的意思,它与你在 Java 中的例子相匹配。
Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.
给定一个指定散列元素或数组元素的表达式,如果散列或数组中的指定元素曾经被初始化,即使相应的值未定义,也返回真。
This indicates it only applies to hash or array elements!
这表明它仅适用于哈希或数组元素!
回答by Axeman
There is no exists
for a SCALARin Perl, anyway. The Perl way is
有没有exists
一个标量在Perl,反正。Perl的方式是
defined( $x )
and the equivalent Java is
等价的Java是
anInteger != null
Those are the equivalents.
这些是等价物。
exists $hash{key}
Is like the Java
就像Java
map.containsKey( "key" )
From your example, I think you're looking for
从你的例子中,我认为你正在寻找
if ( startIn != null ) { ...
if ( startIn != null ) { ...
回答by BV45
For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:
对我来说,只使用 Integer.toString() 方法就可以了。如果您只想非常,如果它为空,您可以将其转换。下面的例子:
private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null || Integer.toString(greenIn) == null )
回答by John Schneider
This should help.
这应该有帮助。
Integer startIn = null;
// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
e.printStackTrace();
}
// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
// (again optional)
if (dontContinue == true) {
//Do-some-error-fix
}