0

The text file, just as a test run, I am using has 12 lines. I want the output to be 12. I keep getting 0 as my output. What is going wrong? I have coded thousands of these methods for school and can literally not figure out why this one does not work. Please help, I am losing my sanity to a simple method.

public static int countLines(String inFileName) {

    int numLines = 0;
    try {
        Scanner scFile = new Scanner(inFileName);
        String line = scFile.nextLine();
        while (!(line.equalsIgnoreCase("")) && scFile.hasNext()) {
            numLines++;
            line = scFile.nextLine();
            scFile.next();
        }
        scFile.close();
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }

    return numLines;
}
Nicktar
  • 5,288
  • 1
  • 24
  • 40
  • *Curious:* Why `equalsIgnoreCase("")` and not just `equals("")`? There are no letters, so no case to ignore. Better yet, why not `line.isEmpty()`? – Andreas Feb 10 '20 at 08:12
  • `nextLine()` reads a line of text. `next()` reads a token. If a line contains only one token, then the `nextLine()` following the `next()` finds that the rest of the line is empty, and the loop ends. – Andreas Feb 10 '20 at 08:13
  • also if the file has an empty line, the loop ends... – Nicktar Feb 10 '20 at 08:14

2 Answers2

0

How about work with IO Package

int noOfLines = 0;
BufferedReader reader;
try {
    reader = new BufferedReader(new FileReader("myfile.txt"));
    String line = reader.readLine();
    while (line != null) {
        //System.out.println(line);
        // read next line
        line = reader.readLine();
        noOfLines++;        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(noOfLines);
Swarit Agarwal
  • 1,916
  • 19
  • 29
-1

Try this :-

    Stream<String> stream= Files.lines(Paths.get("file path"));
    return stream.count();
Gaurav Dhiman
  • 763
  • 4
  • 10