简体   繁体   中英

Why doesn't else if work?

The user enters 3 numbers and I'm assuming all are proper integers and distinct. I'm trying to get the program to print out a sequence starting from the number of the lowest value to the highest value. Why doesn't my else if work here? Or am I making some glaring mistake in the code?

The code is not complete, I've only written this far and then tested it. When I input 8 then 2 and then 4, I intend it to print out 2,3,4,5,6,7,8, but it doesn't. Instead it prints out 4,5,6,7,8,

    System.out.print("Enter a number: ");
    int n1 = Integer.parseInt(in.readLine());
    System.out.print("Enter a number: ");
    int n2 = Integer.parseInt(in.readLine());
    System.out.print("Enter a number: ");
    int n3 = Integer.parseInt(in.readLine());

    if ((n1 > n2) | (n2 > n3)) {
        for (int i = n3; (i <= n1); i++) {
            System.out.print(i + ",");
        }
    }
    else if ((n1 > n3) | (n3 > n2)) {
        for (int i = n2; (i <= n1); i++) {
            System.out.print(i + ",");
        }
    }
    }
}

Your logic is faulty. When n1 = 8 , n2 = 2 , and n3 = 4 , n1 > n2 is true, so your code ends up taking the first path (looping from n3 to n1 ). The value of n3 isn't even taken into account.

Keep in mind that, if you go with your current approach, you'll need about six "else if" clauses to handle all the possible combinations of starting and ending variables. You may have better luck figuring out what the minimum and maximum values are, assigning those to two variables, and looping on the values between those two values. It'll save you a lot of typing.

Presumably, in your first condition, you want to say "n1 is greater than n2, and n2 is greater than n3". However, the "and" operator is written as && , not as | (which is a bit-level "or" operator). Thus, your first condition ( n1 > n2 ) is sufficient to satisfy the first if , so else doesn't apply.

The java logical OR operator is || , not | which stands for BITWISE OR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM