为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕少森 2022-06-04 17:33:50
我遇到了一个问题,我认为这是将字符与数字进行比较。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。
查看完整描述

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

    }

}


查看完整回答
反对 回复 2022-06-04
?
慕森王

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在第一条评论中提到的,变量通常是驼峰式,所以它们不是以大写字母开头。


查看完整回答
反对 回复 2022-06-04
?
不负相思意

TA贡献1777条经验 获得超10个赞

正如评论中的其他人所述,这种对字符的数学比较操作基于每个字符的实际 ASCII 值。所以我建议你使用ASCII 表作为参考来重构你的逻辑。



查看完整回答
反对 回复 2022-06-04
  • 3 回答
  • 0 关注
  • 307 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号