Briana February 2016

Using \r in Java for Count Down Timer

how to use \r in Java properly for Count Down Timer? i want to count down from 20 to 0 and print this, i want to update this instead of writing in new line so i used \r . it works, but when it comes to 10, then after this, instead of writing 9 it writes 90, 80 and so on... plz update my code to solve problem. thanks here is my code

int timer1=20;
int timer2=0;
String timer3="\r";
while(timer1>timer2){
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}  
System.out.print(timer3+timer1);   
System.out.flush(); 
timer1--;}

Answers


DaveRlz February 2016

Your variable names ae confusing to say the least. The problem you are having is that the \r is taking you to the start of the line and you are not overwriting the previous output so that when you write out the number 9 you are still left with the 0 from 10.

Change this line:

   System.out.print(timer3+timer1); 

to:

   System.out.print(timer3+timer1+ " "); 

and this should fix things.

Post Status

Asked in February 2016
Viewed 1,618 times
Voted 7
Answered 1 times

Search




Leave an answer