开发者

What's the problem with this code in Java?

I want to write the time, from 0: 0 to 23:59 for 5 times, but this code will write it in an infinite loop, I can't stop it, until I don't exit eclipse :) What's the problem with this?

class ido {
    public static void main (String[] args){
        int ora = 0;
        int perc = 0;
        System.out.println(ora + ": " + perc);

        for (int i = 1; i <= 5;){
        while (ora <= 24 && perc <= 60){
     开发者_Go百科       perc++;
                if (perc == 60){
                    perc = 0;
                    ora++;
                }
                if (ora == 24){
                    ora = 0;
                    i++;
                }
                System.out.println(ora + ": " + perc);

                }
        }
    }
    }


As pointed out by others, the problem is that the while loop can never terminate because you are resetting the values of the loop control variables inside the loop.

A more normal way of writing this would be as three nested loops:

for (int day=1; day <= 5; day++) {
  for (int hour=0; hour <= 23; hour++) {
    for (int minute=0; minute <= 59; minute++) {
      System.out.println( hour + ":" + minute );
    }
  }
}


for loop is missing a clause, try adding i=i; ora and perc never becomes >24 and >60, so the while loop never breaks.


Well you always reset your ora and perc values so the while loop will never break.
Try resetting your ora value to 0 before the while loop (instead of where you do it now). That way the while will break when ora is 24 and after 5 repeats your for will end.


ora <= 24 && perc <= 60

ora will never be 24 (because it will be set to 0 in first IF)

and perc will never be 60 (because it will bet set to 0 in second IF)

that is the reason for the infintie loop


The problem is that you will never exit your while loop (as ora and perc are reset to 0). So your condition in for loop is irrelevant.


Why are you writing this code this way? There are far better ways that are simpler to do it.

class DoIt {
    public static void main(String[] args) {
        for(int i=0; i<5; i++) {
           for(int hour=0;hour<24; hour++) {
              for(int minute=0;minute<60;minute++) {
                 System.out.printf("%d:%d%n", hour, minute);
              }
           }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜