我刚开始在学校学习Java,现在我被卡住了.
public static void main(String[] args) {
int count = 0;
int point = 5;
while(point != count++){
System.out.println(count);
}
Run Code Online (Sandbox Code Playgroud)
控制台:1 2 3 4 5
为什么数字"5"仍然打印?是不是这个while循环应该只在点!= count + 1时运行?然后它应该在5 = 5时停止,不是它(并且不会打印"5")?
非常感谢.
Man*_*dis 12
point != count++
Run Code Online (Sandbox Code Playgroud)
这意味着比较point和count不等式的当前值然后递增count.所以count4 岁时:
point(不平等)进行比较count 将成为5point再次进行比较(相等)++count在比较中使用该值之前,前缀增量运算符将递增.
OPK*_*OPK 10
因为您==在增量之前进行比较++,如果要修复它,请更改为++count
假设当前结构,我同意关于问题细节的先前答案.但是,最好遵循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++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用"payload"来表示循环所在的代码,在这种情况下只是println调用.
我的不变量是:
count上在测试到来既是将要测试的值,如果它通过测试,将在有效负载中使用的值.count增加了1.循环包含两个带副作用的操作,即调用println和count增量.它们中的每一个都是其声明中最外层的操作.
这是java中prefix(++i)和postfix(i++)运算符之间的区别.
你使用的是postfix,这意味着它首先返回count的值,然后增加它.如果你使用point != ++count你就不会打印5