问候,
我正在尝试验证我的整数是否为空.如果是,我需要提示用户输入值.我的背景是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);
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为Java期望布尔逻辑.
在Perl中,我可以使用"exists"来检查散列/数组元素是否包含以下数据:
@items = ("one", "two", "three");
#@items = ();
if (exists($items[0])) {
print "Something in \@items.\n";
}
else {
print "Nothing in \@items!\n";
}
Run Code Online (Sandbox Code Playgroud)
在Java中有这种方法吗?谢谢您的帮助!
耶利米
PS Perl 存在信息.
Joh*_*lla 41
parseInt()如果解析无法成功完成,则会抛出异常.您可以改为使用Integers相应的对象类型,这样可以使事情变得更加清晰.所以你可能想要更接近的东西:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Run Code Online (Sandbox Code Playgroud)
请注意,如果您决定使用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.
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
146894 次 |
| 最近记录: |