String.equalsIgnoreCase仅对第一个switch case

时间:2017-04-25 05:08:19

标签: java string

在下面给出的代码中我解析文本文件中的字符时,analyze(String word)函数仅在第一次调用时才返回正确的值。之后,即使String等于比较的String(或者至少看起来像它),它也会为每个其他String返回false。为什么呢?

void parsing() throws IOException {
    FileInputStream in = null;
    FileOutputStream out = null;

    String inAddress = "Text To Be Parsed.txt";
    String outAddress = "Copied File.txt";
    in = new FileInputStream(inAddress);
    out = new FileOutputStream(outAddress);
    int c;
    String word = "";
    while ((c = in.read()) != -1) {
        if (c != 13) {
            if (c == '.') {
                System.out.println(word);
                System.out.println(analyse(word));
                word = "";
            } else {
                word += (char) c;
            }
        }
    }
String analyse(String word) throws IOException {

    switch (word.toLowerCase()) {
    case "hello":
        return "English";
    case "konnichiwa":
        return "Japanese";
    case "anneyong":
        return "Korean";
    case "guten tag":
        return "German";
    case "bonjour":
        return "French";
    case "bonjorno":
        return "Italian";
    case "como esta":
        return "Spanish";
    default:
        return "Error";
    }
}

以下是我的文字档案:

  

您好。

     

Konnichiwa。

     

Anneyong。

     

的Bonjour。

     

Guten标签。

     

Bonjorno。

     

Como esta。

以下是此代码的输出:

Hello
English

Konnichiwa
Error

Anneyong
Error

Bonjour
Error

Guten tag
Error

Bonjorno
Error

Como esta
Error

3 个答案:

答案 0 :(得分:2)

你的话语比你需要的更多信息(新行字符).. enter image description here

这就是为什么你的分析方法永远不会与你正在阅读的单词相匹配的原因,你需要在调用 analyze 方法之前摆脱新的行char。

答案 1 :(得分:0)

更简单的解决方案是使用BufferedReader和readLine

BufferedReader in
        = new BufferedReader(new FileReader(inAddress));

String c;
while ((c = in.readLine()) != null) {

        String word = c.replace (".", "");        
        System.out.println(word);
        System.out.println(analyse(word));
}

答案 2 :(得分:0)

正如ΦXocę 웃 Пepeúpa ツ所提到的,这里的问题是你在忽略\r个字符时只考虑\n个字符,所以在这里进行函数调用时,它的参数为\n+Word,而它应该只有Word

因此,您可以修改if循环的while条件,并添加character不应为\n的其他条件。

您可以将if条件修改为:if (c != 13 && c != 10) \\10 is Ascii value for \n

代码:

while ((c = in.read()) != -1) {
    if (c != 13 && c!=10) {
        if (c == '.') {
            System.out.println(word);
            System.out.println(analyse(word));
            word = "";
        } else {
            word += (char) c;
        }
    }
}

这将解决您的问题。另一种更好的方法是使用trim()方法从该单词中删除unwanted white spaces。因此,您可以在switch参数中使用此函数来消除单词中的white spaces

可以将switch条件更改为switch (word.toLowerCase().trim())