You should use a thread for this instead of constantly printing out the time. See the post above if that's what you (most likely) need; however, for purposes of learning what you did wrong, here's an explanation.
You are not updating your hour and minute variables as time goes on.
For example, if you ran this program at 2:52, before you enter the while loop, hours would initially be 2, and minutes would initially be 52. Then, once you enter the while loop, hours=2, and minutes=52, and will never change.
In other words, once you enter the scope of the while loop, as indicated by the {
and }
, you will not run the previous three statements above the while loop ever again.
Also, since the while loop will evaluate a condition, you can just replace your k==1
trick with true
, which is a condition which will always evaluate to true. Both ways are equivalent, but the latter is more elegant.
Here is a solution:
while (true) {
Calendar now= Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute=now.get(Calendar.MINUTE);
System.out.println(hour);
System.out.println(minute);
}