Reputation: 323
Friends I have a piece of code that reads a text file and search for the matching word but there is uncertainty while searching through the text file. Sometimes it is able to match the words and sometimes it doesn't although the word exists in the text file.
Here is the code:
EditText et = (EditText) findViewById(R.id.editText1);
String display = null;
String search = "dadas";
//String current = "woot";
try {
InputStream is = getAssets().open("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(br.readLine() != null){
if(search.equalsIgnoreCase(br.readLine())){
display = "found";
break;
}
}
br.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
et.setText(display);
Here is my text file content:
dadaist
dadaists
dadas
daddies
daddle
daddled
daddles
daddling
Can anyone figure out why is this happening? Suppose i add a word "finish" in my text file and then search it, it will always find it. But if my search word is "dadas" or "dadist" it yield null in the et.
Upvotes: 1
Views: 334
Reputation: 8049
You're calling br.readLine()
twice, which means you'll skip every other line. In your case, "dadas" was on line 3, which meant it was skipped.
Try:
String line = br.readLine();
while(line != null){
if(line.equalsIgnoreCase(search)){
display = "found";
break;
}
line = br.readLine();
}
Upvotes: 1
Reputation: 36806
It looks like you're skipping every other line by calling br.readLine()
twice
I would do something like this instead
search = search.toLowerCase();
String line = null;
while((line = reader.readLine()) != null){
if(line.toLowerCase().contains(search)){
display = "found";
break;
}
}
Upvotes: 1