代码在 txt 文件中找不到字符串。我的代码有什么问题吗?
我编写这段代码是为了查看 txt 文件并找到用户作为输入提供的字符串。我的 txt 文件包含这样的行(此信息稍后会很重要):
第一行 - 空白。 第二条线——伊丹 第三行 - yosi
现在,如果用户输入“idan”作为用户(不带“”),代码就会找到它。如果用户输入“yosi”,它将找不到它。就像我的代码只读取第二行。我是编程新手,这只是我学习如何读写文件的练习,请耐心等待。
这是代码(有一个 catch 和 else 语句,但由于长度原因而被省略):
//Search for 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{
}
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 for 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{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是这样的:
您正在阅读额外的一行。您会发现它会读取您的实现中的每隔一行。即2、4、6号线等
The problem is this:
you are reading an additional line. You will find it reads every other line with your implementation. That is line 2,4,6,etc
问题出在以下地方:
您不需要再次读取它,因为您已经在 while 循环中读取了它:
所以,您基本上读取了 line1 (不对其执行任何操作),然后读取 line2 (执行某些操作)与它)并且该过程重新开始。
The problem is in the following place:
You don't need to read it again because you have already read it in the while loop:
So, you basically read line1 (do nothing with it), then read line2 (do something with it) and the process starts over.
你想做类似的事情
...
串线;
while((line = br.readLine()) != null) {
...
。
每次调用 BufferedReader.readLine() 都会从文件中读取下一个可用行 由于您读取了 while 语句中的一行并读取了 if 语句中的下一行,因此您只检查偶数行。
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 thewhile
statement and read the next line for theif
statement, you're only checking the even numbered lines.