Piku
Piku

Reputation: 21

Counting the number of items in a file using java

I have a text file:

2|BATH BENCH|19.00
20|ORANGE BELL|1.42
04|BOILER ONION|1.78

I need to get the number of items which is 3 here using JAVA. This is my code:

int Flag=0;
    File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        Flag=Flag+1;
    }

It is going in an infinite loop. Can someone please help? Thank you.

Upvotes: 0

Views: 64

Answers (3)

Swapnil Padaya
Swapnil Padaya

Reputation: 695

In the code you have written

int Flag=0;
    File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) { // this line is just checking whether there is next line or not.
        Flag=Flag+1;
    }

When you write while (sc.hasNextLine()){} it check whether there is nextLine or not. eg
line 1 : abcdefg
line 2: hijklmnop

here your code will just be on line 1 and keep telling you that yes there is a nextLine.

Whereas when you write

while(sc.hasNextLine()){
sc.nextLine();
Flag++;
}

Scanner will read the line 1 and then because of sc.nextLine() it will go to line 2 and then when sc.hasNextLine() is checked it gives false.

Upvotes: 1

Alin
Alin

Reputation: 314

while (sc.hasNextLine()) {
  Flag=Flag+1;
  String line = sc.nextLine(); //Do whatever with line
}

Upvotes: 1

Milgo
Milgo

Reputation: 2767

You must get the next line to avoid an endless loop.

int Flag = 0;
File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
    sc.nextLine();
    Flag++;
}

Upvotes: 1

Related Questions