3 回答

TA贡献1815条经验 获得超6个赞
您可以使用查找“表”,我使用了String:
private static final String LOOKUP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
然后将字符与 进行比较indexOf(),但它看起来很乱,可能更容易实现,我现在想不出更容易的东西:
String FindCountry = "9Z";
Map<String, String> Cont = new HashMap<>();
Cont.put("BA-BE", "Angola");
Cont.put("9X-92", "Trinidad & Tobago");
for (String key : Cont.keySet()) {
if (LOOKUP.indexOf(key.charAt(0)) == LOOKUP.indexOf(FindCountry.charAt(0)) &&
LOOKUP.indexOf(FindCountry.charAt(1)) >= LOOKUP.indexOf(key.charAt(1)) &&
LOOKUP.indexOf(FindCountry.charAt(1)) <= LOOKUP.indexOf(key.charAt(4))) {
System.out.println("Country: " + Cont.get(key));
}
}

TA贡献1777条经验 获得超3个赞
如果您只使用字符A-Zand 0-9,您可以在两者之间添加一个转换方法,这将增加0-9字符的值,因此它们将在 之后A-Z:
int applyCharOrder(char c){
// If the character is a digit:
if(c < 58){
// Add 43 to put it after the 'Z' in terms of decimal unicode value:
return c + 43;
}
// If it's an uppercase letter instead: simply return it as is
return c;
}
可以这样使用:
if(applyCharOrder(key.charAt(0)) == applyCharOrder(findCountry.charAt(0))
&& applyCharOrder(findCountry.charAt(1)) >= applyCharOrder(key.charAt(1))
&& applyCharOrder(findCountry.charAt(1)) <= applyCharOrder(key.charAt(4))){
System.out.println("Country: "+ cont.get(key));
}
在线尝试。
注意:这是一个包含十进制 unicode 值的表。字符'0'-'9'将具有值48-57并将'A'-'Z'具有值65-90。所以 the< 58用于检查它是否是一个数字字符,并且 the+ 43将增加48-57to 91-100,将它们的值置于 the 之上,'A'-'Z'这样你的<=和>=检查就会按照你的意愿工作。
或者,您可以创建一个查找字符串并将其索引用于订单:
int applyCharOrder(char c){
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".indexOf(c);
}
PS:正如@Stultuske在第一条评论中提到的,变量通常是驼峰式,所以它们不是以大写字母开头。
添加回答
举报