Search code examples
javastringwhile-loopiterationnested-loops

The first while loop of the nested loop iterates only once


Comparing two .txt files here, results the line number of the first file if any string in the second file matches or repeats in the first.

Here in the code, the first while loop iterates only once.

 Scanner scanner = new Scanner(firstFile);
 Scanner scanner1 =new Scanner(secondFile);
 int lineNum = 0;
 while (scanner.hasNextLine())  
  {
        String line = scanner.nextLine();
        lineNum++;
        while (scanner1.hasNextLine()) 
        {
               String line1 = scanner1.nextLine();
               if(line.contains(line1)) 
                { 
                  System.out.println("Ignore/Review line number: "+lineNum);      
                }
        }
  }             

Solution

  • You have to create the Scanner of the second file inside the outer while loop:

    Scanner scanner = new Scanner(firstFile);
    int lineNum = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        lineNum++;
        Scanner scanner1 =new Scanner(secondFile);
        while (scanner1.hasNextLine()) {
            String line1 = scanner1.nextLine();
            if(line.contains(line1)) { 
                System.out.println("Ignore/Review line number: "+lineNum);      
            }
        }
    } 
    

    Otherwise scanner1.hasNextLine() returns false on the second iteration of the outer while loop, since the entire second file was already read on the first iteration of the outer loop.