简体   繁体   English

(Java) While 循环条件

[英](Java) While-Loop condition

I'm just starting to learn Java in school and now I'm stuck.我刚开始在学校学习 Java,现在我被困住了。

public static void main(String[] args) {
    int count = 0;
    int point = 5;
    while(point != count++){
        System.out.println(count);
    }

Console : 1 2 3 4 5控制台:1 2 3 4 5

Why is number "5" still printed ?为什么仍然打印数字“5”? Isn't this while loop supposed to run only if point != count + 1 ?这个 while 循环不应该只在 point != count + 1 时运行吗? Then it should stop when 5 = 5, isn't it (and "5" wouldn't be printed) ?然后它应该在 5 = 5 时停止,是不是(并且不会打印“5”)?

Thank a lot.非常感谢。

point != count++

This means compare point and current value of count for inequality and then increment count .这意味着比较pointcount当前值是否不等,然后增加count So when count is 4 :所以当count为 4 时:

  1. it will be compared to point (unequal)它将与point (不等)进行比较
  2. count will become 5 count将变为 5
  3. the while loop will run for one iteration while 循环将运行一次迭代
  4. it will be compared to point again (equal)它将再次与point进行比较(相等)
  5. the loop is terminated循环终止

the prefix increment operator ++count would increment before using the value in a comparison.前缀递增运算符++count将在比较中使用该值之前递增。

因为你是在 increment ++之前做比较== ,如果你想修复它,改成++count

I agree with the prior answers on the details of your problem assuming the current structure.我同意先前关于假设当前结构的问题细节的答案。 However, it would be better to follow the advice in the Java Language Specification, 15.7.但是,最好遵循 Java 语言规范15.7 中的建议。 Evaluation Order , which says 评估顺序,其中说

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right. Java 编程语言保证运算符的操作数以特定的求值顺序进行求值,即从左到右。

It is recommended that code not rely crucially on this specification.建议代码不要过分依赖此规范。 Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.当每个表达式最多包含一个副作用(作为其最外层操作)时,代码通常会更清晰,并且当代码不依赖于从左到右计算表达式的结果究竟是哪个异常出现时。

The count++ has a side effect and is not the outermost operation in its statement. count++有副作用,不是其语句中最外层的操作。 That is ultimately the cause of your difficulty reasoning about your code.这最终是导致您难以对代码进行推理的原因。 It would be clearer if you did the increment inside the loop, either before or after the println call.如果您在println调用之前或之后在循环内进行增量会更清楚。

The key to reasoning about programs is to have simple, clear invariants.对程序进行推理的关键是拥有简单、清晰的不变量。 Here is an alternative version of your program, over-commented for exposition.这是您的程序的替代版本,为了说明而过度评论。

public class Test {
  public static void main(String[] args) {
    /*
     * Initialize count to the first value that will be used in the loop
     * payload.
     */
    int count = 1;
    int point = 5;
    while (count < point) {
      /*
       * Loop payload - executed with the same value of count as the test above
       */
      System.out.println(count);
      /*
       * Increment count for the next test and, if the test passes, payload
       * execution.
       */
      count++;
    }
  }
}

I am using "payload" to mean the code for which the loop exists, in this case just the println call.我使用“有效负载”来表示存在循环的代码,在这种情况下只是println调用。

My invariants are:我的不变量是:

  • The value of count on arrival at the test is both the value that will be tested and, if it passes the test, the value that will be used in the payload.到达测试时的count既是将要测试的值,也是在通过测试时将在有效载荷中使用的值。
  • After execution of the loop body, the value of count has been incremented by one.循环体执行后, count的值已经加一。

The loop contains two operations with side effects, the call to println and the count increment.该循环包含两个具有副作用的操作,即对println的调用和count递增。 Each of them is the outermost operation in its statement.它们中的每一个都是其语句中最外层的操作。

This is the difference between prefix ( ++i ) and postfix ( i++ ) operators in java.这是java中前缀( ++i )和后缀( i++ )运算符之间的区别。

What you used is postfix, which means it first returns the value of count, and after that increases it.你用的是postfix,这意味着它首先返回count的值,然后增加它。 if you'd use point != ++count you wouldn't get 5 printed如果你使用point != ++count你不会得到 5 打印

The count isn't incremented until after the the while has been evaluated.直到对while进行评估之后,计数才会增加。 You'll need to make it this way instead:你需要这样做:

public static void main(String[] args) {
    int count = 0;
    int point = 5;
    while(point != ++count){
        System.out.println(count);
    }

In this case the ++ causes count to change first, before it is checked against point .在这种情况下, ++导致count首先改变,然后再根据point进行检查。

It's easy to remember: if the ++ comes before, it gets incremented first.很容易记住:如果++出现在前面,则它首先递增。 If after then after the evaluation.如果经过再评价。 The same applies to assignments.这同样适用于任务。

With that said, I agree with Patricia´s answer, that the incrementing should be done within the while block like so:话虽如此,我同意帕特里夏的回答,增量应该在 while 块内完成,如下所示:

  public static void main(String[] args) {
        int count = 0;
        int point = 5;
        while(point != count){
            System.out.println(count);
            count++;
        }

This is more clear and easier to reason about.这更清楚,更容易推理。

The problem is that you are comparing count before incrementing it.问题是您在增加计数之前比较计数。

What you mean is: while(point != count +1)你的意思是: while(point != count +1)

What you want : while(point != ++count)你想要什么: while(point != ++count)

Hope that helps!希望有帮助!

This is what I understand: if you use prefix or post in a for loop it does not change the behaviour of the programme at all.这就是我的理解:如果你在 for 循环中使用 prefix 或 post 它根本不会改变程序的行为。 so the question is when does it matter?所以问题是什么时候重要?

it matters when we use prefix or postfix alongside other comparison operators FOR EXAMPLE当我们将前缀或后缀与其他比较运算符一起使用时很重要例如

prefix i = 1;前缀i = 1; result = 5 + ++i //answer for this one will be 7 Explanation : this is what I think - because it has ++ before "i" then first we will increment the i and then add it to 5. result = 5 + ++i //这个答案将是 7解释:这就是我的想法 - 因为它在“i”之前有 ++ 然后首先我们将增加 i 然后将其添加到 5。

postfix后缀

i=1;我=1; result = 5 + i++;结果 = 5 + i++; //answer for this will be 6 Explanation: because this one has ++ after i then first we will add the i value and then increment so first 1 will be added to 5 and then it the new value of i will be 2 //对此的答案将是 6解释:因为这个在 i 之后有 ++ 然后首先我们将添加 i 值然后递增所以第一个 1 将被添加到 5 然后它的新值 i 将是 2

In short i++ first provide the value to comparison operator and then it is incremented.简而言之, i++ 首先将值提供给比较运算符,然后递增。 This explain your case 5!= 4 , then i is incremented to 5 and printed.这解释了你的情况 5!= 4 ,然后 i 增加到 5 并打印。

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

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