Home > database >  Java if statement within while loop not functioning properly
Java if statement within while loop not functioning properly

Time:10-01

I am having an issue with some java code I have I created, I am attempting to create an if statement contained within a while loop in order for it to run indefinitely while rotating between different print commands based on a variable that is increased each time it goes through the loop. The code should be setting the time variable to 0 and then entering the while loop. The first thing it should always do within the while loop is increase the time variable by one with and then entering the if statement and printing one of the three different possible print commands, and then when the time variable is larger then 24 setting time to 0 and therefore looping back to the first possible print command. I am still learning java and am absolutely terrible at it so my apologies if this question is dumb.

the code:

class Main {
  public static void main(String[] args) {
    int time = 0;
    while (true) {
      time  ;
      if (time > 5) {
        System.out.println("Good morning.");
      } else if (time > 12) {
        System.out.println("Good afternoon.");
      } else if (time > 19) {
        System.out.println("Good night.");
      } else if (time > 24) {
        time = 0;
      } else {
        System.out.println("If this message is printed, the code is not working properly.");
      }
    }
  }
}

CodePudding user response:

Your if statements to not cover the case when time is between 0 and 5. As such when "time" starts at these values your else statement with the error message will be hit

CodePudding user response:

Your code is never able to reach the 12, 19, and 24 conditions. If the time is say 13, the if statement will first check if the time is greater than 5, which 13 is. So it will enter the first block and print "Good Morning".

To fix this you could change the order that you are checking the time, so that the largest checks come first and if not will fall through to the smaller checks. Try something like this:

class Main {
  public static void main(String[] args) {
    int time = 0;
    while (true) {
      time  ;
      if (time > 24) {
        time = 0;
      }else if (time > 19) {
        System.out.println("Good night.");
      } else if (time > 12) {
        System.out.println("Good afternoon.");
      } else if (time > 5) {
        System.out.println("Good morning.");
      } else {
        System.out.println("If this message is printed, the code is not working properly.");
      }
    }
  }
}
  •  Tags:  
  • java
  • Related