lundi 28 décembre 2020

Why is Java skipping an if clause if they contain similar comparisons?

So, I just started to get my hands dirty on Java this week and I found something rather odd. I'll add the code and then walk you through.

import java.util.Scanner;

public class kids
{
    public static void main(String[] args)
    {
        System.out.println("How old are you, doll?");
        
        Scanner scanner = new Scanner(System.in);
        int age = scanner.nextInt();

        System.out.println("Doggie lover or a cat person?");
        String animal = scanner.nextLine();
        
        if(age < 18 && animal.contains("dog")) // 1st comparison
        {
            System.out.println("Hello cutie, welcome");
        }
        else if(age < 18 && animal.contains("cat")) // 2nd comparison
        {
            System.out.println("Oh, hi"); // This statement gets skipped
        }
        else if(age < 18 && animal.contains("cat")); // 3rd comparison
        {
            System.out.println("Hiya, Doggie lover!");
        }
    }
}

I've attached my output here Output

So, I gave an input "dogcat" to the string animal. It is pretty clear or at least to me that the three comparisons should return TRUE but my output says otherwise. Seems like only the first and the third comparisons return TRUE but clearly if the third comparison returns TRUE since it contains the string "cat" so does the second comparison. Why is Java skipping my comparison here?

Aucun commentaire:

Enregistrer un commentaire