Reputation: 37
I am reading a file which has multiple lines, example of the content of this file is:
Reader : INFO - LOOP with sapces : 1
Reader : INFO - LOOP with sapces : 2
Reader : INFO - LOOP with sapces : 17
Reader : INFO - LOOP with sapces : 201
What I am trying to do is to get my program to read the number of lines that contains LOOP with spaces.
Here is my code:
Scanner fileScan = new Scanner(file);
int iterated = 0;
while (fileScan.hasNext())
{
String somestring = fileScan.next();
if (somestring.matches(".*LOOP\\swith\\sspaces.*"))
{ iterated++; }
}
}
System.out.println("number of times found is: "+iterated);
My issue is that my program is 0 for int iterated.
Upvotes: 0
Views: 214
Reputation: 23002
What I am trying to do is to get my program to read the number of lines that contains LOOP with spaces
Try Like this.
if (scanner.nextLine().contains("LOOP with spaces"))
{ iterated++; }
This method will read whole line.
String line=scanner.nextLine();
This will return next token in file means
next()
can read the input only till the space.
String token=scanner.next();
Upvotes: 3
Reputation: 1168
Scanner#next() returns a next element up to the next instance of the delimiter pattern, which is be default "\\s"
, so it read up the next space, not line.
If you change hasNext()
and next()
to hasNextLine()
and nextLine()
, the delimiter is the system newline character, so it will read in a whole line at once.
Upvotes: 1