简体   繁体   English

为什么还不行呢?

[英]Why doesn't else if work?

The user enters 3 numbers and I'm assuming all are proper integers and distinct. 用户输入了3个数字,我假设所有数字都是正确的整数且互不相同。 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. 当我输入8,然后输入2,然后输入4时,我打算打印2、3、4、5、6、7、8,但不是。 Instead it prints out 4,5,6,7,8, 而是打印出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 ). n1 = 8n2 = 2n3 = 4n1 > n2为真,因此您的代码最终将走第一条路径(从n3循环到n1 )。 The value of n3 isn't even taken into account. 甚至不考虑n3的值。

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. 请记住,如果继续使用当前的方法,则需要大约六个“ else if”子句来处理开始变量和结束变量的所有可能组合。 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". 大概,在第一个条件下,您想说“ n1大于n2,n2大于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. 因此,您的第一个条件( n1 > n2 )足以满足第一个if ,因此else不适用。

The java logical OR operator is || Java逻辑OR运算符为|| , not | ,不是| which stands for BITWISE OR 代表BITWISE OR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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