Code doesn't find string in txt file. Whats wrong with my code?
I'm writing this code to look inside a txt file and find me a string that the user gave as input. My txt file contains the lines as such (this info will be important later):
first line - blank. second line - idan third line - yosi
now, if the user inputs "idan" as the user (without the "") the code will find it. If the user puts in "yosi" it wont find it. It's like my code is reading only the second line. I'm new in programming and this is just a practice for me to learn how to read and write to files, please be patient with me.
here is the code (there is a catch and also the else statement but they where left off for length reasons):
//Search fo开发者_如何学编程r the specific profile inside.
try{
BufferedReader br = new BufferedReader(new FileReader("d:\\profile.txt"));
System.out.println("Searching for your Profile...");
int linecount = 0;
String line;
while (br.readLine() !=null){
linecount++;
if(userName.contentEquals(br.readLine())){
System.out.println("Found, " + userName + " profile!");
break;
}
else{
}
The problem is this:
*if(userName.contentEquals(br.readLine())){*
you are reading an additional line. You will find it reads every other line with your implementation. That is line 2,4,6,etc
The problem is in the following place:
if(userName.contentEquals(br.readLine()))
You don't need to read it again because you have already read it in the while loop:
while (br.readLine() !=null)
So, you basically read line1 (do nothing with it), then read line2 (do something with it) and the process starts over.
You want to do something like ... String line; while((line = br.readLine()) != null) { ... }
Every call to BufferedReader.readLine()
reads the next available line from the file. Since you read one line in the while
statement and read the next line for the if
statement, you're only checking the even numbered lines.
精彩评论