I am trying to make a cross-platform console progress indicator in Java. Therefore, I use the System.out.printf method to print the percentage:
System.out.printf("\t%2.2f%%\b\b\b\b\b\b", percentage);
and I put this in a for loop. The problem I am facing is that it does not print anything until the for for loop completes. This is an example program showing the problem:
public class Test { public static void main(String[] args) { for(int i =0; i<5000; i++){ System.out.printf("\b\b\b\b\b\b%2.2f%%", ((float) i/5000f)*100f); System.out.flush(); } } }
I think the problem has something to do with compiler optimization, but I'm not sure. It is strange that System.out.println prints when the for loop is running.
Edit: I forgot to add it to the problem. But I already tried to flush the buffer. It does not matter. Adding %n to the end of my printf line works, but it starts a new line, I really need it to reuse the current line.
All opposing solutions work. But they only work in real consoles. Not a netbeans or eclipse console.
source share