英文:
Needing help understanding logic in "Head First Java"
问题
我最近开始第一次使用Java进行编程(只是一种爱好),目前我正在使用一本非常好的书《Head First Java》,但我真的很难理解这些练习。
就像这个例子一样:
class Output {
void go() {
int y = 7;
for(int x = 1; x < 8; x++) {
y++; // y现在是8吗?
if(x > 4) {
System.out.println(++y + " "); // 这会使y = 9吗?
}
if(y > 14) {
System.out.println(" x = " + x);
break; // break关键字如何影响循环的其余部分?
}
}
}
public static void main(String[] args) {
Output o = new Output();
o.go();
}
}
有人能否请解释一下这段代码中发生了什么?
英文:
I have recently started programming in Java for the first time (just as a hobby), and at the moment Im working with a book "Head First Java" that is very good, but I'm really struggling with understanding the exercises.
Like this for example:
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();
}
}
Can someone please explain to me what goes on in this code?
答案1
得分: 1
变量y
必须为15,因为您在for
循环中多次增加了它的值。
++y
将其值增加1。i++
和++i
非常相似,但并不完全相同。两者都会递增数字,但++i
会在当前表达式求值之前递增数字,而i++
会在表达式求值之后递增数字。
break
只是简单地跳出循环。
英文:
Variable y
must be 15, because you increased it's value many times with the for
loop.
++y
increases it's value by 1. i++
and ++i
are very similar but not exactly the same. Both increment the number, but ++i
increments the number before the current expression is evaluted, whereas i++
increments the number after the expression is evaluated.
break
simply exists from the loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论