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在第一條評論中提到的,變量通常是駝峰式,所以它們不是以大寫字母開頭。
添加回答
舉報