需要帮助理解《Head First Java》中的逻辑。

huangapple go评论59阅读模式
英文:

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 &lt; 8; x++) {
            y++;                                 // is y now 8?
            if(x &gt;4) {
                System.out.println(++y + &quot; &quot;);  // does this make y = 9?
            }
            if(y &gt; 14) {
                System.out.println(&quot; x = &quot; + 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.

huangapple
  • 本文由 发表于 2020年10月22日 18:16:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64480153.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定