-1

I have created this While loop to read lines from a text file. How to I stop the loop after it has found the values?

     try
    {
       BufferedReader file = new BufferedReader(new FileReader("Inventory.txt"));
       while (file.ready())
       {
          String ID = file.readLine();
          String Name = file.readLine();
          String Price = file.readLine();

          if (Value.equals(tf_ID.getText()))
          {
             System.out.println(Name +"  "+ Price);
          }
       }
    }
    catch (IOException e)
    {
       System.out.println("Error");
    }
 }
Mat
  • 202,337
  • 40
  • 393
  • 406
user2838611
  • 19
  • 1
  • 4

2 Answers2

2

Use keyword break, here is link with reference to branching in java:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

John
  • 5,189
  • 2
  • 38
  • 62
1

Make use of break; in your if statement, it will cause the while loop to stop.

if (Value.equals(tf_ID.getText()))
{
    System.out.println(Name +"  "+ Price);
    break;//your while loop will stop
}
Akzwitch
  • 113
  • 1
  • 2
  • 13