0

Why this code is an infinity loop? How I can fix it?

Calendar cal = new GregorianCalendar();
cal.setTime(new Date());

while (cal.SECOND < 20){
    System.out.println(cal.SECOND);
}

Thanks you in advance for yours help

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
rates336
  • 11
  • 1
  • 3
  • I strongly recommend you don’t use `Calendar`. That class is poorly designed and long outdated. Instead use for example `LocalTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 30 '22 at 11:59
  • Does this answer your question? [How to get new time in Java?](https://stackoverflow.com/questions/36482581/how-to-get-new-time-in-java) Does [this?](https://stackoverflow.com/questions/14451872/calendar-month-gives-wrong-output) [This?](https://stackoverflow.com/questions/54626533/below-code-is-printing-static-system-time-for-every-two-seconds-but-i-want-to-pr) – Ole V.V. May 30 '22 at 12:00

1 Answers1

0

I will get answer, SECOND is a constant variable. If you will get return Second with Calendar class you will wrote:

cal.get(Calendar.SECOND); 
//or
cal.getTime().getSeconds();

If someone know why intelIJ crosses out "getSeconds()", but this working please enter answer here or know what is, a difference between these codes.

Thanks you in advance for yours help.

rates336
  • 11
  • 1
  • 3
  • First, this does not break your infinite loop from the question. *If someone know why intelIJ crosses out "getSeconds()",* That’s because you are calling the `getSeconds` method of `Date`, a method that has been deprecated for more than 25 years because it works unreliably across time zones, which in turn means that you should not use it. BTW you should neither use the `Date` nor the `Calendar` class at all. Use java.time. – Ole V.V. May 30 '22 at 12:05