Conditions,  Java

Conditions in Java : If…Else

Conditional logic is common practice when different actions or tasks are required to be performed on input or data and is based on specific conditions being met.

If…else

Scenario: Evaluate the user’s input to determine if the input is a valid month in a year and output the quarter of the year that the month exists in.

import java.util.Scanner;

public class ConditionExampleForIf {

   public static void main(String[] args) {
      
      var scanner = new Scanner(System.in);
      System.out.print("Enter a month number (1-12) : ");
      var monthNumber = scanner.nextInt();

      String message = null;
      if (monthNumber < 1 || monthNumber > 12) {
         message = "That is not a valid month!";
      } else if (monthNumber <= 3) {
         message = "That is in quarter 1";
      } else if (monthNumber <= 6 ) {
         message = "That is in quarter 2";
      } else if (monthNumber <= 9) {
         message = "That is in quarter 3";
      } else if (monthNumber <= 12) {
         message = "That is in quarter 4";
      }
      System.out.println(message);
   }
}

Scenario: Determine which quarter of the year the current date exists in.

import java.time.LocalDateTime;

public class ConditionExampleForIf {

   public static void main(String[] args) {
      
      var now = LocalDateTime.now();
      var monthNumber = now.getMonthValue();

      String message = null;
      if (monthNumber <= 3) {
         message = "That is in quarter 1";
      } else if (monthNumber <= 6 ) {
         message = "That is in quarter 2";
      } else if (monthNumber <= 9) {
         message = "That is in quarter 3";
      } else if (monthNumber <= 12) {
         message = "That is in quarter 4";
      }
      System.out.println(message);
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *