Question

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.

Was it helpful?

Solution

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++; }
  • nextLine()

This method will read whole line.

String line=scanner.nextLine();
  • next()

This will return next token in file means next() can read the input only till the space.

String token=scanner.next();

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top