0

I'm using threads in java to print a counter and increase it every one second. I want the counter to be printed on the previous counter value, but what is actually happening is that the counter is being printed in a new place. How can I do that?

Here is the code and the output in Netbeans:

package threads;

public class Threads extends Thread {

    public static int counter = 0;
    
    static synchronized void incrementCounter() {
          System.out.print(counter );
          counter++;
     }

     @Override
     public void run() {
          while(counter<1000){
               incrementCounter();              
              try {
                  sleep(1000);
              } catch (InterruptedException ex) {

              }
          }
     }

     public static void main(String[] args) {
          Threads te = new Threads();         
          te.start();
     } 
}

This is the output:

012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061...
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
  • Do you want the new printed counter to replace the text of the previous one? So after 5 loops, the console will just show 4 instead of 01234? –  Mar 23 '22 at 18:00
  • 1
    You can use a console library that suports curses-like functionality, or print backspaces over the previous contents manually. – Dave Newton Mar 23 '22 at 18:00
  • That is exactly what i want, sorry that the output is not being shown because i'm new in stack overflow @coopikoop – Ahmed Redwan Mar 23 '22 at 18:03
  • Does this answer your question? [Write to same location in a console window with java](https://stackoverflow.com/questions/5859588/write-to-same-location-in-a-console-window-with-java) – pringi Mar 23 '22 at 18:05
  • @AhmedRedwan Don't post expected output in images. Post it as formatted text. – Ted Klein Bergman Mar 23 '22 at 18:07
  • @TedKleinBergman done – Ahmed Redwan Mar 23 '22 at 18:11

1 Answers1

0

You can achieve that by replacing your

System.out.print(counter );

By

System.out.printf("%s", "\u0008\u0008\u0008\u0008" + counter );

\u0008 is Backspace.

pringi
  • 3,987
  • 5
  • 35
  • 45
  • 1
    You should probably change the number of backspaces according to what's been printed, as otherwise it'll delete other content. – Ian Newson Mar 23 '22 at 18:17