Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current line number from bufferedReader

I have different text files I would like to read, and I am using BufferedReader for it like this:

int theMax = 0;
    int theTypes = 0;
    int []theSlices = {};
    /*
        INPUT1:
        17 4
        2 5 6 8  

        INPUT2:
        100 10
        4 14 15 18 29 32 36 82 95 95                                

    */

    try {
        FileReader reader = new FileReader("INPUT1.in");
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            String[] numbers = line.split(" ");

            System.out.println(numbers[0]);
            System.out.println(line);
        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    ;

My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.

Example for INPUT1: theMax = 17 theTypes = 4 theSlices = 2 5 6 8

like image 222
Chris Avatar asked Aug 08 '26 00:08

Chris


1 Answers

Very simple: you keep track yourself.

    String line;
    int currentLine = 0;

    while ((line = bufferedReader.readLine()) != null) {
        String[] numbers = line.split(" ");

        System.out.println("Linenumber " + currentLine);
        System.out.println(numbers[0]);
        System.out.println(line);
        currentLine ++;
    }
    reader.close();
like image 57
kutschkem Avatar answered Aug 09 '26 12:08

kutschkem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!