Zwiebel
Zwiebel

Reputation: 1615

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){
            perc++;
                if (perc == 60){
                    perc = 0;
                    ora++;
                }
                if (ora == 24){
                    ora = 0;
                    i++;
                }
                System.out.println(ora + ": " + perc);

                }
        }
    }
    }

Upvotes: 0

Views: 206

Answers (6)

Dave Costa
Dave Costa

Reputation: 48111

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 );
    }
  }
}

Upvotes: 3

Joseph Ottinger
Joseph Ottinger

Reputation: 4951

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);
              }
           }
        }
    }
}

Upvotes: 1

ewan.chalmers
ewan.chalmers

Reputation: 16235

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.

Upvotes: 1

oers
oers

Reputation: 18704

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

Upvotes: 1

Deelazee
Deelazee

Reputation: 513

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.

Upvotes: 1

Steven Feldman
Steven Feldman

Reputation: 841

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

Upvotes: 1

Related Questions