我编写的方法检查给定的String输入是否可以解析为正整数。
有没有更简洁的方法来写这个,所以我不重复拒绝该值的代码?
try {
int num = Integer.parseInt(value);
if (num <= 0) {
errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}
} catch (NumberFormatException e) {
errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}
答案 0 :(得分:1)
一个简单的方法:
int num = 0;
try {
num = Integer.parseInt(value);
} catch (NumberFormatException e) {
num = -1;
}
if (num <= 0) {
errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}
答案 1 :(得分:1)
我相信这是你能得到的清洁工。 即使它传递给try,如果它不在你期望的结果范围内,也会强制它进入catch。
try {
int num = Integer.parseInt(value);
if (num <= 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}