java - 确定字符是否为有效十六进制数字的方法?
问题描述
所以我不断收到一个错误,说它在“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;
}
解决方案
您可以使用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;
}
推荐阅读
- python - 用户特定的主页 Django
- rust - 忽略 Mutex 上的中毒错误的最简单方法是什么?
- java - Springboot集成测试中无法使用TestConfiguration
- python - 压缩文件在到达流结束标记之前结束
- ios - NativeScript - 在 iOS 构建中使用“BottomNavigation”时如何解决此崩溃?
- c# - 在 C# Visual Studio 中没有为一个或多个必需参数提供值
- postgresql - pgAdmin 的“服务器”选项卡为空(Docker Compose)
- node.js - Nestjs UnhandledPromiseRejectionWarning: TypeError: this.flushLogs is not a function
- android - 如何使用数据绑定在 recyclerview 中获取选定的 textView 值(当前位置)?
- angular - Angular 10 - 以字符串形式提供的清理样式和脚本