Search code examples
javaintleap-year

Printing two integers


This could be simple but i just can't get around it at the moment practice question. I'm just trying to print a few integers together so that output would be

2004 is a leap year

2013 is not a leap year

public class Ex1partA {
       public static void main(String[] args) {
       int year  = 2004;
       if(year%400==0){
           System.out.println("2004 is a leap year");
       }else if(year%100==0){
           System.out.println("2004 is not a leap year");
       }else if(year%4==0){
           System.out.println("2004 is a leap year");
       }else{
           System.out.println("2004 is not a leap year");
       }
   }
  
   {
        int year1  = 2013;
        if(year1%400==0){
        System.out.println("2013 is a leap year");
        }else if(year1%100==0){
        System.out.println(" 2013 is not a leap year");
        }else if(year1%4==0){
        System.out.println("2013 is a leap year");
        }else{
        System.out.println("2013 is not a leap year");
    
   }
 }
}

Solution

  • You are over thinking it. Just use a simple if-else like this.

    int year = 2004;
    if (year % 4 == 0) {
        System.out.println("2004 is a leap year");
    } else {
        System.out.println("2004 is not a leap year");
    }
    
    int year1 = 2013;
    if (year1 % 4 == 0) {
        System.out.println("2013 is a leap year");
    } else {
        System.out.println("2013 is not a leap year");
    }
    

    You could even move this to a method where you can just pass the year and it'd display the result for you. Something like this

    public static void main(String[] args) {
    
        int year = 2004;
        checkLeapYear(year);
    
        int year1 = 2013;
        checkLeapYear(year1);
    }
    
    private static void checkLeapYear(int year) {
        if (year % 4 == 0) {
            System.out.println(year + " is a leap year");
        } else {
            System.out.println(year + " is not a leap year");
        }
    }