问题描述
最近,我第一次开始用Java编程(只是出于业余爱好),目前,Im正在写一本非常好的书《 Head First Java》,但是我在理解练习方面确实很挣扎。
例如:
class Output {
void go() {
int y = 7;
for(int x = 1; x < 8; x++) {
y++; // is y Now 8?
if(x >4) {
System.out.println(++y + " "); // does this make y = 9?
}
if(y > 14) {
System.out.println(" x = " + x);
break; // how does the break key word affect the rest of the loop?
}
}
}
public static void main(String[] args) {
Output o = new Output();
o.go();
}
}
有人可以向我解释这段代码中发生了什么吗?
解决方法
变量y
必须为15,因为您通过for
循环将其值增加了很多次。
++y
将其值增加1。i++
和++i
非常相似,但不完全相同。两者都会增加数字,但是++i
会在评估当前表达式之前增加数字,而i++
会在评估表达式之后增加数字。
break
仅存在于循环中。