简体   繁体   English

代码在txt文件中找不到字符串。 我的代码有什么问题?

[英]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. 我正在编写此代码以查找txt文件内部,并找到一个用户输入的字符串。 My txt file contains the lines as such (this info will be important later): 我的txt文件包含这样的行(此信息稍后将很重要):

first line - blank. 第一行-空白。 second line - idan third line - yosi 第二行-IDAN第三行-YOSI

now, if the user inputs "idan" as the user (without the "") the code will find it. 现在,如果用户输入“ idan”作为用户(不带“”),则代码将找到它。 If the user puts in "yosi" it wont find it. 如果用户输入“ yosi”,它将找不到它。 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): 这是代码(有一个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{

                }

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 那是第2、4、6行等

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循环中阅读了它:

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. 因此,您基本上读取了line1(不执行任何操作),然后读取line2(不执行任何操作),过程重新开始。

You want to do something like ... String line; 您想做类似...字符串的事情; while((line = br.readLine()) != null) { ... } while((line = br.readLine())!= null){...}

Every call to BufferedReader.readLine() reads the next available line from the file. 每次对BufferedReader.readLine()调用都会从文件中读取下一个可用行。 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. 由于您在while语句中读取了一行,而在if语句中读取了下一行,因此只检查偶数行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM