if else statement

just23
just23 used Ask the Experts™
on
My question is why output is 3 and not 2 as I expected?

public class CheckNumber{

public static void main(String []args){
int i = 0;
int j = 0;

if (i > 10)
      j = 1;
else if (i == 0)
      if (j == 100)
      j = 2;
      else
            j = 3;
      else
            j = 4;
                  
      System.out.println(j);
      }
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
j is 3 because i is 0. You haven't modified the i before it hits the nested if, therefore i is not less greater than 10 (so j does not equal 4), and i does not equal 100 (so j does not equal 2), therefore i equals 0 and j equals 3. Try the code below and let me know if that does what you need it to:

if (i > 10)
      j = 1;
else if (i == 100)
      if (j == 0)
      j = 2;
      else
            j = 3;
      else 
            j = 4;

Open in new window

High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
Commented:
If you format it like this, does it make more sense?
public static void main(String []args){
    int i = 0;
    int j = 0;

    if (i > 10)
        j = 1;
    else if (i == 0)
        if (j == 100)
            j = 2;
        else
            j = 3;
    else 
        j = 4;
                 
    System.out.println(j);
}

Open in new window


This is why should always use the enclosing brackets, to make it clear which lines belong to which BLOCK:
public static void main(String []args){
    int i = 0;
    int j = 0;

    if (i > 10) {
        j = 1;
    } else if (i == 0) {
        if (j == 100) {
            j = 2;
        } else {
            j = 3;
        }
    } else { 
        j = 4;
    }
                 
    System.out.println(j);
}

Open in new window

Author

Commented:
I got it. thanks a lot lads

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial