百分位分数
parseInt vs isDigit
如果参数是 0 到 255(包括 0 和 255)之间的整数的字符串表示形式,我需要我的代码 return true,否则为 false。
例如:
字符串“0”、“1”、“2”....“254”、“255”是有效的。
填充字符串(例如“00000000153”)也是有效的。
isDigit 显然也可以工作,但我想知道这是否会更有用 and/or 这甚至可以与填充字符串一起工作吗?
public static boolean isValidElement(String token) {
int foo = Integer.parseInt("token");
if(foo >= 0 && foo <= 255)
return true;
else
return false;
}
您可以使用正则表达式:
return token.matches("1?\d{1,2}|2[0-4]\d|25[0-5]");
因此,如果字符串不是有效数字,Integer.parseInt 将抛出 NumberFormatException,请记住这一点。
我会使用 commons-math3 库中的 NumberUtils.isDigit() 来检查,然后使用 Integer.valueOf 这是一个高效的数字解析器。
if (NumberUtils.isDigit(token)) {
int foo = Integer.valueOf(token);
return (foo >=0 && foo <=255);
}
isDigit
不行,因为它需要一个字符作为输入,而 returns 如果它是 0 到 9 的数字则为真。 [参考:isDigit javadoc]
由于在您的情况下您需要测试从 0 到 255 的所有数字的字符串表示,因此您必须使用 parseInt
.
此外,还检查传递的令牌是否为有效数字,方法是捕获 NumberFormatException
并在它不是有效整数的情况下返回 false。
public static boolean isValidElement(String token) {
try{
int foo = Integer.parseInt(token);
if(foo >= 0 && foo <= 255)
return true;
else
return false;
} catch (NumberFormatException ex) {
return false;
}
}
Integer.parseInt throws a NumberFormatException 如果无法转换。考虑到这一点,您可以使用此代码片段。 不需要额外的依赖项。
public static boolean isValidElement(String token) {
try {
int value = Integer.parseInt(token);
return value >= 0 && value <= 255;
} catch(NumberFormatException e) {
return false;
}
}
如果参数是 0 到 255(包括 0 和 255)之间的整数的字符串表示形式,我需要我的代码 return true,否则为 false。
例如: 字符串“0”、“1”、“2”....“254”、“255”是有效的。
填充字符串(例如“00000000153”)也是有效的。
isDigit 显然也可以工作,但我想知道这是否会更有用 and/or 这甚至可以与填充字符串一起工作吗?
public static boolean isValidElement(String token) {
int foo = Integer.parseInt("token");
if(foo >= 0 && foo <= 255)
return true;
else
return false;
}
您可以使用正则表达式:
return token.matches("1?\d{1,2}|2[0-4]\d|25[0-5]");
因此,如果字符串不是有效数字,Integer.parseInt 将抛出 NumberFormatException,请记住这一点。
我会使用 commons-math3 库中的 NumberUtils.isDigit() 来检查,然后使用 Integer.valueOf 这是一个高效的数字解析器。
if (NumberUtils.isDigit(token)) {
int foo = Integer.valueOf(token);
return (foo >=0 && foo <=255);
}
isDigit
不行,因为它需要一个字符作为输入,而 returns 如果它是 0 到 9 的数字则为真。 [参考:isDigit javadoc]
由于在您的情况下您需要测试从 0 到 255 的所有数字的字符串表示,因此您必须使用 parseInt
.
此外,还检查传递的令牌是否为有效数字,方法是捕获 NumberFormatException
并在它不是有效整数的情况下返回 false。
public static boolean isValidElement(String token) {
try{
int foo = Integer.parseInt(token);
if(foo >= 0 && foo <= 255)
return true;
else
return false;
} catch (NumberFormatException ex) {
return false;
}
}
Integer.parseInt throws a NumberFormatException 如果无法转换。考虑到这一点,您可以使用此代码片段。 不需要额外的依赖项。
public static boolean isValidElement(String token) {
try {
int value = Integer.parseInt(token);
return value >= 0 && value <= 255;
} catch(NumberFormatException e) {
return false;
}
}