我刚开始在学校学Java,现在我被困住了。
public static void main(String[] args) {
int count = 0;
int point = 5;
while(point != count++){
System.out.println(count);
}控制台:1 2 3 4 5
为什么"5“号还在印?这个while循环不应该只在point != count +1的情况下运行吗?那么它应该在5 =5时停止,不是吗( "5“不会被打印出来)?
非常感谢。
发布于 2015-12-23 15:21:50
point != count++这意味着比较point和count的当前值对于不等式,然后增量count。因此,当count为4时:
point (不平等)相比较count将变成5point进行比较(相等)前缀增量运算符++count将在使用比较中的值之前增加。
发布于 2015-12-23 15:19:02
因为要在增量==之前执行比较++,所以如果要修复它,请更改为++count。
发布于 2015-12-23 15:33:43
假设目前的结构,我同意先前关于你的问题的细节的答案。但是,最好遵循Java语言规范( 15.7.评价顺序 )中的建议。
Java编程语言保证操作符的操作数似乎是按照特定的计算顺序计算的,即从左到右。 建议代码不要依赖于此规范。当每个表达式最多包含一个副作用时,作为其最外层的操作,以及当代码不完全依赖于由左向右计算表达式的结果而产生的异常时,代码通常更清晰。
count++有副作用,在其语句中不是最外层的操作。这最终是导致您难以对代码进行推理的原因。如果您在循环中执行增量,无论是在println调用之前还是之后,都会更清楚。
程序推理的关键是要有简单、清晰的不变量。这里是你的程序的另一个版本,评论太多了。
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++;
}
}
}我使用“有效负载”来表示循环存在的代码,在本例中仅指println调用。
我的不变量是:
count的值既是将要测试的值,如果它通过测试,则是在有效负载中使用的值。count的值增加了一个。该循环包含两个副作用操作,调用println和count增量。它们中的每一个都是语句中最外层的操作。
https://stackoverflow.com/questions/34438684
复制相似问题