如何在Java中比较字符和数字

我遇到了一个问题,我认为这是将字符与数字进行比较。


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));


  }

}

在这种情况下,代码打印“安哥拉”,但如果


String FindCountry = "9Z" 

它不打印任何东西。我不确定我认为问题在于它无法比较'2'大于'Z'。在那个例子中,我只有两个 Cont.put(),但在我的文件中,我得到了更多,而且其中很多不仅仅是字符。我和他们有问题。


将 char 与 number 进行比较的最聪明和最好的方法是什么?实际上,如果我设置一个规则,比如“1”大于“Z”,那没关系,因为我需要这种更大的方式:AZ-9-0。


慕少森
浏览 308回答 3
3回答

红糖糍粑

您可以使用查找“表”,我使用了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()) {&nbsp; &nbsp; if (LOOKUP.indexOf(key.charAt(0)) == LOOKUP.indexOf(FindCountry.charAt(0)) &&&nbsp; &nbsp; &nbsp; &nbsp; LOOKUP.indexOf(FindCountry.charAt(1)) >= LOOKUP.indexOf(key.charAt(1)) &&&nbsp; &nbsp; &nbsp; &nbsp; LOOKUP.indexOf(FindCountry.charAt(1)) <= LOOKUP.indexOf(key.charAt(4))) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Country: " + Cont.get(key));&nbsp; &nbsp; }}

慕森王

如果您只使用字符A-Zand 0-9,您可以在两者之间添加一个转换方法,这将增加0-9字符的值,因此它们将在 之后A-Z:int applyCharOrder(char c){&nbsp; // If the character is a digit:&nbsp; if(c < 58){&nbsp; &nbsp; // Add 43 to put it after the 'Z' in terms of decimal unicode value:&nbsp; &nbsp; return c + 43;&nbsp; }&nbsp; // If it's an uppercase letter instead: simply return it as is&nbsp; return c;}可以这样使用:if(applyCharOrder(key.charAt(0)) == applyCharOrder(findCountry.charAt(0))&nbsp; &nbsp; && applyCharOrder(findCountry.charAt(1)) >= applyCharOrder(key.charAt(1))&nbsp; &nbsp; && applyCharOrder(findCountry.charAt(1)) <= applyCharOrder(key.charAt(4))){&nbsp; 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){&nbsp; return "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".indexOf(c);}PS:正如@Stultuske在第一条评论中提到的,变量通常是驼峰式,所以它们不是以大写字母开头。

不负相思意

正如评论中的其他人所述,这种对字符的数学比较操作基于每个字符的实际 ASCII 值。所以我建议你使用ASCII 表作为参考来重构你的逻辑。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java