Home > Software engineering >  Static counter that increments for every line printed in output?
Static counter that increments for every line printed in output?

Time:10-08

I have a long output, and I am trying to number the lines printed in the output to make sure all of them are printing correctly. I would just use a regular counter in my method, but I am using recursion to print everything, so it has been hard to get an accurate count of the number of lines being printed. How could I make some sort of static counter that prints before each line is printed to essentially number each line?

CodePudding user response:

You can just create something like CounterHolder and increment it every time you are trying to get value:

public class CounterHolder{

    private static int counter = 0;

    private CounterHolder(){}

    public static int getCounter(){
        return counter  ;
    }

}

UPD:

You can also add custom printing method here:

public class CounterHolder{

    private static int counter = 0;

    private CounterHolder(){}

    public static void print(String msg){
        System.out.println(String.format("%d -> %s", counter  , msg));
    }

}
  • Related