Java字符无法正确识别

时间:2015-04-19 19:12:06

标签: java unicode

我不明白为什么以下代码:

public Image getLetter(String letterToGet)
{
    System.out.println("é" == "e");

    System.out.println("Received: " + letterToGet);

    if("\u00e9" == letterToGet.toLowerCase()); {
        letterToGet = "SPECIALACCTAIGUESPECIAL";
    }
    if("\u00e8" == letterToGet.toLowerCase()) {
        letterToGet = "SPECIALACCTGRAVESPECIAL";
    }

    System.out.println("searching for " + letterToGet + " in the hashmap");
    return languageMap.get(letterToGet.toLowerCase());
}

可以返回以下输出

Traduction following ArrayList: [e, é, è]
Received: e
searching for SPECIALACCTAIGUESPECIAL in the hashmap
Received: é
searching for SPECIALACCTAIGUESPECIAL in the hashmap
Received: è
searching for SPECIALACCTAIGUESPECIAL in the hashmap

遵循这个逻辑,为什么这一行返回false?

System.out.println("\u00e9" == "e");

2 个答案:

答案 0 :(得分:2)

请记住,e!=é和u00e9 =é,这将返回true:

System.out.println("\u00e9" == ("é"));//Notice é instead of e

请注意,即使这种情况在这种情况下有用,因为我们比较了字符文字(在评论中解释为@Pshemo),请确保将较长的字符串与.equals进行比较。

答案 1 :(得分:2)

意外输出的原因是在第一个if之后的额外分号。

目前,你有

if("\u00e9" == letterToGet.toLowerCase()); {
    letterToGet = "SPECIALACCTAIGUESPECIAL";
}

其中letterToGet的分配超出了if的范围,因此无论letterToGet的值是什么,它都会运行。