简体   繁体   中英

Searching for string in file and returning that specific line

I am working on student registration system. I have a text file with studentname, studentnumber and the student's grade stored in every line such as:

 name1,1234,7
 name2,2345,8
 name3,3456,3
 name4,4567,10
 name5,5678,6

How can I search a name and then return the whole sentence? It does not get any matches when looking for the name.

my current code look like this:

public static void retrieveUserInfo()
{
    System.out.println("Please enter username"); //Enter the username you want to look for
    String inputUsername = userInput.nextLine();


    final Scanner scanner = new Scanner("file.txt");
    while (scanner.hasNextLine()) {
       final String lineFromFile = scanner.nextLine();
       if(lineFromFile.contains(inputUsername)) { 
           // a match!
           System.out.println("I found " +inputUsername+ " in file " ); // this should return the whole line, so the name, student number and grade
           break;
       }
       else System.out.println("Nothing here");
    }

The problem is with Scanner(String) constructor as it:

public Scanner(java.lang.String source)

Constructs a new Scanner that produces values scanned from the specified string.

Parameters: source - A string to scan

it does not know anything about files, just about strings. So, the only line that this Scanner instance can give you (via nextLine() call) is file.txt .

Simple test would be:

Scanner scanner = new Scanner("any test string");
assertEquals("any test string", scanner.nextLine());

You should use other constructor of Scanner class such as:

Scanner(InputStream)
Scanner(File)
Scanner(Path)

You already have the variable that holds the whole line. Just print it like this:

while (scanner.hasNextLine()) {
       final String lineFromFile = scanner.nextLine();
       if(lineFromFile.contains(inputUsername)) { 
           // a match!
           System.out.println("I found " +lineFromFile+ " in file " ); 
           break;
       }
       else System.out.println("Nothing here");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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