Reputation: 321
In my code given below where I am parsing characters from a text file, the analyse(String word) function is returning the right value only for the first time its called. After that, it returns false for every other String even when the String is equal to the compared String (or at least seems like it). Why?
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";
}
}
The following is my text file:
Hello.
Konnichiwa.
Anneyong.
Bonjour.
Guten tag.
Bonjorno.
Como esta.
The following is the output of this code:
Hello
English
Konnichiwa
Error
Anneyong
Error
Bonjour
Error
Guten tag
Error
Bonjorno
Error
Como esta
Error
Upvotes: 1
Views: 1520
Reputation: 2489
As ΦXocę 웃 Пepeúpa ツ
mentioned, The problem here is that you are considering only \r
characters to not to be taken while you are ignoring \n
characters So here when the fuction call is made, It has argument as \n+Word
while It should be Word
only.
So you can modify the if
condition of while
loop and add another condition that the character
should not be \n
.
You can modify the if condition as : if (c != 13 && c != 10) \\10 is Ascii value for \n
Code:
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;
}
}
}
This will solve your problem. Another and better approach is to use trim()
method which eleminates unwanted white spaces
from the word. So you can use this function in switch
argument to eliminate the white spaces
from the word.
It can be done by changing switch
condition as switch (word.toLowerCase().trim())
.
Upvotes: 0
Reputation: 44814
A simpler solution would be use a BufferedReader and 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));
}
Upvotes: 0
Reputation: 48258
Your words are holding more info than you need (new line chars)..
that is the reason why your analyse method never match the words you are reading, you need to get rid off the new line char before calling the analyse method..
Upvotes: 2