Search code examples
javaif-statementcontains

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?


Solution

  • For input dogcat, it only executes the first if condition. Since other two conditions are given as else if conditions, they do not get executed.

    Confusion happens because of the typo of having an semicolon just after the 3rd if condition. So the typo makes an empty statement for 3rd if condition.

    The statements in the last set of curly braces are not a part of 3rd if condition due to the typo.