Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 验证给定字符串是否可以转换为正整数_Java_Integer - Fatal编程技术网

Java 验证给定字符串是否可以转换为正整数

Java 验证给定字符串是否可以转换为正整数,java,integer,Java,Integer,我编写了一个方法,用于检查给定的字符串输入是否可以解析为正整数 有没有更干净的方法来编写此代码,这样我就不会重复拒绝该值的代码 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 pos

我编写了一个方法,用于检查给定的字符串输入是否可以解析为正整数

有没有更干净的方法来编写此代码,这样我就不会重复拒绝该值的代码

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");
}
试试看{
int num=Integer.parseInt(值);
如果(num一种简单的方法:

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");
 }
int num=0;
试一试{
num=整数.parseInt(值);
}捕获(数字格式){
num=-1;
}

如果(num我相信这是你能得到的清洁剂。 即使它通过了尝试,如果它不在你期望的结果范围内,你也会强迫它进入捕捉

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");
}
试试看{
int num=Integer.parseInt(值);

if(num)我认为你不应该重复你的拒绝消息,因为你有两种不同的拒绝场景。或者你可以简单地抛出一个新的NumberFormatException if num