user2874583
user2874583

Reputation: 535

Print counting in loop java

I have a java program that simulates values and returns them. But I want to see how far the simulation is by printing the current state.

Ex:

System.out.print("Number of simulations: ");
for(int i=0;i<NUMBER_OF_SIMULATIONS;i++){

/* Do my calcutions*/

System.out.print("\b" + i);
}

I thougth this was possible, but the output is: Number of simulations: 0?1?2?3?4?5?6?7?8?9?10?11?12?

I only want to see the current state, so not a counter. So if i++ current i removes and i+1 will shown.

Upvotes: 0

Views: 819

Answers (2)

Fappaz
Fappaz

Reputation: 3656

\b will go back 1 char. As Pawel Veselov said, use \r to go to the beginning of the line. Another important thing is that, depending on where you're testing the output (IDE), it won't work as expected. You should test in a shell (Windows cmd or Linux terminal) in order to see the real result.

Upvotes: 1

Ed Morales
Ed Morales

Reputation: 1037

If you where expecting to edit the value to have one line being:

Number of simulations: 0 //and then editing just the number to have

Number of simulations: 1 

Its not possible on the command line to my knowledge.. every time you call System.out.print you are writing/adding the value into the "out" stream, hence the count being added every time is called at the end of the line with print().

You would need to add a new line for every time you print it.

System.out.println("Number of Simulations: " + i);

And that will give you a new line everytime.

Edit: Its not what you want, but thats a cleaner way to visualize it and how programs normally log steps.

Upvotes: 0

Related Questions