简体   繁体   English

java 方法 Character.isDigit(char) 返回 true,输入为 'O'

[英]The java method Character.isDigit(char) returns true with an input of 'O'

I made a for loop to iterate through a given string and used the Character.isDigit(char) to return true ONlY if all of the letters in the string were digits.我创建了一个 for 循环来遍历给定的字符串,并使用 Character.isDigit(char) 如果字符串中的所有字母都是数字,则仅返回 true。 For example isInteger("412") returns true.例如 isInteger("412") 返回真。 BUT, with an input of the string "1O1" it returns true, which should be false since O is a letter.但是,输入字符串“1O1”时,它返回真,这应该是假的,因为 O 是一个字母。

public boolean isInteger(String str)
{
    for(int i = 0; i < str.length(); i++){
        if(Character.isDigit(str.charAt(i))){
            return true;
        }
    }
return false;
}

I also tried making a condition putting:我也尝试过提出条件:

if(str.charAt(i) != 'O' && Character.isDigit(str.charAt(i))){
            return true;
        }

But that did not work.但这没有用。

Your method is returning true if ANY of the characters in the string are digits.如果字符串中的任何字符都是数字,则您的方法将返回 true。 Two of the characters in 1O1 are digits, so the method will return true. 1O1中的两个字符是数字,因此该方法将返回 true。

You need to check if any of the characters is not a digit:您需要检查是否有任何字符不是数字:

for(int i = 0; i < str.length(); i++){
    if(!Character.isDigit(str.charAt(i))){
        return false;
    }
}
return true;

All of the characters have to be numbers for the condition to be true.所有字符都必须是数字才能使条件为真。 If any character is not a number, the condition is false.如果任何字符不是数字,则条件为假。

public boolean isInteger(String str)
{
    if (str == null || str.length() == 0) return false;

    for (int i = 0; i < str.length(); i++) {
        if(!Character.isDigit(str.charAt(i))) {  // not condition
            return false;
        }
    }

    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM