Search code examples
javastringbufferedreaderfilereader

Java reading a string from a text(txt) file


Rod
Rae
Bryan
Shiroe
Ric
Kirito
Asuna
Elsa
Akutabe
Shino

I have that list saved in a text file. If I were to enter Rod, it should say "Exists" and if I enter a name that is not on the list, it should say "Does not exist." But what is happening on my code is that it reads the file per line and prints "Does not exist" if it does not match the string line. So if I were to enter a name that does not exist in the txt file, it would print 10 "Does not exist" lines.

This is my code below:

Scanner in = new Scanner(System.in);
    out.print("Enter name: ");
    String name = in.nextLine();

    BufferedReader br = new BufferedReader(new FileReader("name.txt"));
    String line;
    while ((line = br.readLine()) != null) {
        if (line.contains(name)) {
            out.println("Exists");
            break;
        } else {
            out.println("Does not exist");
        }
    }
    br.close();

An example of a what would be output is:

name = Kirito

Does not exist
Does not exist
Does not exist
Does not exist
Exists

Why does my program print so many Does not exist before finding the exact match?


Solution

  • You're breaking the loop if the name exists, so you should only print the "not exists" message if the loop doesn't break:

    Scanner in = new Scanner(System.in);
    out.print("Enter name: ");
    String name = in.nextLine();
    
    BufferedReader br = new BufferedReader(new FileReader("name.txt"));
    String line;
    boolean nameFound = false;
    while ((line = br.readLine()) != null) {
        if (line.contains(name)) {
            out.println("Exists");
            nameFound = true;
            break;
    }
    if (!nameFound) {
        out.println("Does not exist");
    }
    br.close();