如何测试输入字符串中的非数字字符,如果找到非数字字符,则返回false。
private static boolean luhnTest(String number){
int s1 = 0, s2 = 0;
String reverse = new StringBuffer(number).reverse().toString();
for(int i = 0 ;i < reverse.length();i++)
{
int digit = Character.digit(reverse.charAt(i), 10);
if(i % 2 == 0){//this is for odd digits, they are 1-indexed in the algorithm
s1 += digit;
}
else
{//add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
s2 += 2 * digit;
if(digit >= 5)
{
s2 -= 9;
}
}
}
return (s1 + s2) % 10 == 0;
}
发布于 2015-07-29 21:40:12
一种方法是使用正则表达式("\d*"
),请参阅Pattern类。另一种方法是简单地使用Integer.parseInt (...)
(或Long.parseLong( ...)
)并捕获异常。
发布于 2015-07-29 21:48:27
去掉所有的数字,看看是否还剩下什么:
public class DigitsCheck{
public static boolean isOnlyDigits(String input) {
return (input.replaceAll("\\d", "").length() == 0);
}
public static void main(String []args){
System.out.println(isOnlyDigits("abc123"));
System.out.println(isOnlyDigits("123"));
}
}
产生
false
true
https://stackoverflow.com/questions/31701924
复制相似问题