Search code examples
javabufferedreadersplitfile-read

Buffered Reader read certain line and text


This is my first post, so i'm not sure how things work here. Basically, i need some help/advice with my code. The method need to read a certain line and print out the text after the inputted text and =

The text file would like

A = Ant

B = Bird

C = Cat

So if the user it input "A" it should print out something like

-Ant

So far, i manage to make it ignore "=" but still print out the whole file

here is my code:

public static void readFromFile() {
    System.out.println("Type in your word");
    Scanner scanner = new Scanner(System.in);
    String input = scanner.next();
    String output = "";
    try {
        FileReader fr = new FileReader("dictionary.txt");           
        BufferedReader br = new BufferedReader(fr);            
        String[] fields;
        String temp;
        while((input = br.readLine()) != null) {
            temp = input.trim();
            if (temp.startsWith(input)) {
                String[] splitted = temp.split("=");
                output += splitted[1] + "\n";
            }
        }
        System.out.print("-"+output);
    }
    catch(IOException e) {

    }
}

Solution

  • It looks like this line is the problem, as it will always be true.

    if (temp.startsWith(input))
    

    You need to have a different variables for the lines being read out of the file and for the input you're holding from the user. Try something like:

    String fileLine;
    while((fileLine = br.readLine()) != null)
        {
            temp = fileLine.trim();
            if (temp.startsWith(input))
            {
                String[] splitted = temp.split("=");
                output += splitted[1] + "\n";
            }
        }