KJ94
KJ94

Reputation: 11

If within an if statement Java

I'm having some trouble inserting an if statement within an if statement. When the first 'if condition' is met, it still utilises the 'else' statement. Is there a way I can rewrite my code so that the 'else' statement is not being utilised. I thought that if the first 'if condition' was met then it would not check the else statement. I know I could use a switch statement, but I wanted to compare and contrast the uses of switch and if statement to gain a better understanding of Java. Below is my code. Thanks

    int age = 0;

    if (age == 0)
    {
        {System.out.println("You can crawl");}
        if (age == 1) {
            System.out.println("You can talk");
        } else {
            System.out.println("You can walk");
        }
    }

console: You can crawl You can walk

Upvotes: 0

Views: 835

Answers (2)

Piotr Wilkin
Piotr Wilkin

Reputation: 3491

There are two things you can do:

First of all, if you want exclusive ifs, you can branch them within a series of else if statements, i.e.:

if (age == 0) {
    System.out.println("You can crawl");
} else if (age == 1) {
    System.out.println("You can talk");
} else {
    System.out.println("You can walk");
}

If you really want to utilize branching if statements, the statements really have to branch, i.e. you have to properly nest the brackets:

if (age == 0) { 
    System.out.println("You can crawl");
} else {
    if (age == 1) {
        System.out.println("You can talk");
    } else {
        System.out.println("You can walk");
    }
}

Using an editor that actually formats code for you with proper indentation can help here.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521339

What may be currently happening is that the age == 0 condition is firing true, but then, because of the way you structured the code, the else condition is also firing, as a predicate of the entirely separate if condition checking age == 1. The solution is simple, connect everything via if ... else if ... else logic:

if (age == 0) {
    System.out.println("You can crawl");
}
else if (age == 1) {
    System.out.println("You can talk");
}
else {
    System.out.println("You can walk");
}

Upvotes: 5

Related Questions