'How can i print on the same line in java?
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...
Solution 1:[1]
You can achieve that by replacing your
System.out.print(counter );
By
System.out.printf("%s", "\u0008\u0008\u0008\u0008" + counter );
\u0008 is Backspace.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pringi |
