在下面给出的我从文本文件中解析字符的代码中,analyse(String word)函数仅在首次调用该函数时才返回正确的值。此后,即使该字符串等于比较的字符串(或至少看起来像它),它也会为其他所有字符串返回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";
    }
}


以下是我的文本文件:


  你好。
  
  n日
  
  安勇
  
  你好。
  
  Guten标签。
  
  Bonjorno。
  
  科莫esta。


以下是此代码的输出:

Hello
English

Konnichiwa
Error

Anneyong
Error

Bonjour
Error

Guten tag
Error

Bonjorno
Error

Como esta
Error

最佳答案

您的文字所包含的信息超出了您的需要(换行符)。
java - String.equalsIgnoreCase仅在第一次切换时返回true-LMLPHP

这就是您的分析方法与您所阅读的单词不匹配的原因,您需要在调用分析方法之前摆脱掉换行符。

10-07 12:43
查看更多