首页 > 解决方案 > 确定字符是否为有效十六进制数字的方法?

问题描述

所以我不断收到一个错误,说它在“if (Character.isValidHex(thisChar, 16)) {”行找不到符号,我想知道这个方法的格式是否正确?在确定每个字符是否为数字后,我很难确定每个字符是否为有效的十六进制值 (af)。这是确定有效性的部分,这是我唯一的错误。我必须将使用 isdigit 的部分和确定它是否为十六进制值的部分分开,我不能组合和使用 Character.digit(thisChar, 16) !!!请帮忙!!


public static boolean isValidHex(String userIn) {
    boolean isValid = false;

    // The length is correct, now check that all characters are legal hexadecimal digits
    for (int i = 0; i < 4; i++) {
      char thisChar = userIn.charAt(i);

     // Is the character a decimal digit (0..9)? If so, advance to the next character
      if (Character.isDigit(thisChar)) {
        isValid = true;
      }

      else {
        //Character is not a decimal digit (0..9), is it a valid hexadecimal digit (A..F)?
        if (Character.isValidHex(thisChar, 16)) {
          isValid = true;
        }
        else {
           // Found an invalid digit, no need to check other digits, exit this loop
          isValid = false;
          break;
      }
   }
}    
// Returns true if the string is a valid hexadecimal string, false otherwise
return isValid;
}

标签: javamethodscharacter

解决方案


您可以使用Character.digit(thisChar, 16),因为您已经使用 过滤掉了 0 到 9 Character.isDigit(thisChar)

来自 Javadoc 的Character.digit()

如果基数不在 MIN_RADIX ≤ radix ≤ MAX_RADIX 范围内,或者如果 的值ch不是指定基数中的有效数字,-1则返回

if (Character.digit(thisChar, 16) != -1) {
    isValid = true;
}

推荐阅读