在下面给出的代码中我解析文本文件中的字符时,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
答案 0 :(得分:2)
答案 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())
。