import java.util.*;
class Dis {
static boolean Digitinstring(String s) {
boolean result = false;
int i, j;
char[] ch = s.toCharArray();
int x = ch.length;
for (j = 0; j < x; j++) {
for (i = 0; i <= 9; i++) {
if (ch[j] == i) {
System.out.println("True");
result = true;
} else {
result = false;
}
}
}
return result;
}
public static void main(String args[]) {
System.out.println("Enter the string");
Scanner ob = new Scanner(System.in);
String s = ob.nextLine();
System.out.println(Digitinstring(s));
}
}
此代码始终给出答案 false
。 if 条件不起作用。
我该怎么做才能使其正常工作?
最佳答案
您的代码失败是因为“3”不等于 3。字符 3,即您的 ch[j] 永远不会等于实际整数,因为它们具有不同的类型。如果你想让它工作,你应该用这个替换你的 if 条件:
Character.getNumericValue(ch[j]) == i;
一个更简单的方法是简单地使用
Character.isDigit(s.charAt(j));
你的整个方法看起来像这样:
public static boolean digitInString(String s){
for(int i = 0; i<s.length(); i++){
if(Character.isDigit(s.charAt(i))){
return true;
}
}
return false;
}
关于java - 如何判断字符串中是否有数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32416161/