dimanche 4 avril 2021

Java: Leap year / Problems with prioritization in if-statement

i am trying to determine wether if a given year is a leapyear or not. But when you test the programm with the leapyear 1996, it shows that 1996 is not a leapyear:

import javax.swing.JOptionPane;

public class Leapyear{

    public static void main (String[] args){
    
        var year = Integer.parseInt(JOptionPane.showInputDialog("Year: "));
        
    
        if(year%4==0 
            && year%100!=0

                ^year%4==0 
                    && year%100==0 
                    && year%400==0){
            JOptionPane.showMessageDialog(null,
                        year + " is a leapyear!");
        }
        
        else{
            JOptionPane.showMessageDialog(null,
                        year + " is not a leapyear!");
        }   
    }       
}

As for me: I think this is a prioritization problem, because ^'s priority rating is 8 while &&'s priority rating is 10, so therefore it will check the conditions in the following sequence (starting with ^):

if(year%4==0 && (year%100!=0 ^ year%4==0) && year%100==0 && year%400==0){..}

I think that is the reason why when you test the program with 1996, it won't execute the code in the if statement but in the else one. If so, is there any possibility to check the conditions before ^ first?

Thank you very much for your help!

Aucun commentaire:

Enregistrer un commentaire