Java 如何比较整数的字符串表示形式?
我想知道如何使用if语句,就好像它们是字符串的整数一样Java 如何比较整数的字符串表示形式?,java,string,if-statement,compare,Java,String,If Statement,Compare,我想知道如何使用if语句,就好像它们是字符串的整数一样 /** * * @param token * @return true if parameter is the String representation of an integer * between 0 and 255 (including 0 and 255), false otherwise. * Strings "0", "1", "2" .... "254", "255" are valid. * Padded S
/**
*
* @param token
* @return true if parameter is the String representation of an integer
* between 0 and 255 (including 0 and 255), false otherwise.
* Strings "0", "1", "2" .... "254", "255" are valid.
* Padded Strings (such as "00000000153") are also valid
*/
public static boolean isValidElement(String token) {
if (token=> 0 || token <=255)
return true;
return false;
}
/**
*
*@param令牌
*@return true,如果参数是整数的字符串表示形式
*介于0和255之间(包括0和255),否则为false。
*字符串“0”、“1”、“2”。。。。“254”、“255”有效。
*填充字符串(如“00000000 153”)也有效
*/
公共静态布尔值isValidElement(字符串标记){
如果(token=>0 | | token使用Integer.parseInt(yourString)
来解析字符串中的整数。您可以尝试以下方法:
public static boolean isValidElement(String token) {
try {
Integer n = Integer.parseInt(token);
return (n >= 0 && n <= 255);
} catch (NumberFormatException nfe) {
return false;
}
}
公共静态布尔isValidElement(字符串标记){
试一试{
整数n=整数.parseInt(令牌);
返回(n>=0&&n请尝试以下操作:
if (Integer.parseInt(token) >= 0 || Integer.parseInt(token) <= 255) {
System.out.println(true);
}
if(Integer.parseInt(token)>=0 | | Integer.parseInt(token)您可以使用,但它允许一个前导的+
,根据您的javadoc,这是不允许的
您可以手动测试前导的+
,然后像这样使用Integer.parseInt()
:
public static boolean isValidElement(String token) {
if (token == null || token.isEmpty() || token.charAt(0) == '+')
return false;
try {
int num = Integer.parseInt(token);
return (num >= 0 && num <= 255);
} catch (@SuppressWarnings("unused") NumberFormatException e) {
return false;
}
}
将它们转换为相同基数的整数?查看integer.parseInt()
你不比较苹果和橘子,你比较苹果和苹果,或者橘子和橘子。在这种情况下,使用。为什么n
是一个整数
,而不是int
?——另外,你不应该打印任何东西。非整数值应该简单地返回false
,正如javadoc在问题中定义的那样。不要解析twice、 解析相对来说比较慢。--你不是在“铸造”任何东西,你是在“解析”。
public static boolean isValidElement(String token) {
if (token == null || token.isEmpty())
return false;
// skip leading zeroes
int i = 0;
while (i < token.length() && token.charAt(i) == '0')
i++;
// validate remaining
char ch;
switch (token.length() - i) {
case 0:
return true; // Allow "0"
case 1:
ch = token.charAt(i);
return (ch >= '1' && ch <= '9'); // Allow "1" to "9"
case 2:
ch = token.charAt(i);
if (ch >= '1' && ch <= '9') {
ch = token.charAt(i + 1);
return (ch >= '0' && ch <= '9'); // Allow "10" to "99"
}
return false;
case 3:
ch = token.charAt(i);
if (ch == '1') {
ch = token.charAt(i + 1);
if (ch >= '0' && ch <= '9') {
ch = token.charAt(i + 2);
return (ch >= '0' && ch <= '9'); // Allow "100" to "199"
}
} else if (ch == '2') {
ch = token.charAt(i + 1);
if (ch >= '0' && ch <= '4') {
ch = token.charAt(i + 2);
return (ch >= '0' && ch <= '9'); // Allow "200" to "249"
} else if (ch == '5') {
ch = token.charAt(i + 2);
return (ch >= '0' && ch <= '5'); // Allow "250" to "255"
}
}
return false;
default:
return false;
}
}