我遇到了问题,我认为问题出在将字符与数字进行比较时。
String FindCountry = "BB";
Map<String, String> Cont = new HashMap <> ();
Cont.put("BA-BE", "Angola");
Cont.put("9X-92", "Trinidad & Tobago");
for ( String key : Cont.keySet()) {
if (key.charAt(0) == FindCountry.charAt(0) && FindCountry.charAt(1) >= key.charAt(1) && FindCountry.charAt(1) <= key.charAt(4)) {
System.out.println("Country: "+ Cont.get(key));
}
}
在本例中,代码打印“Angola”,但如果
String FindCountry = "9Z"
它不打印任何内容。我不确定我认为问题在于它无法比较“2”大于“Z”。在那个例子中,我只得到了两个 Cont.put(),但在我的文件中,我得到了更多,而且其中很多不仅仅是字符。我遇到了他们的问题。
比较 char 和 number 的最聪明和最好的方法是什么?实际上,如果我设置一个规则,比如“1”大于“Z”,那就没问题了,因为我需要这种更大的方式:A-Z-9-0。
谢谢!
最佳答案
您可以使用查找“表”,我使用了字符串
:
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));
}
}
关于java - Java中如何比较字符和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54534967/