【问题标题】:Why does the output change so drastically just because of the change in location of the statement in the while loop?为什么仅仅因为 while 循环中语句位置的变化,输出会发生如此剧烈的变化?
【发布时间】:2017-12-20 23:58:36
【问题描述】:

好吧,在尝试理解 while 循环的总体概念时,我遇到了这个..

public static void main (String[] args) {

    int x = 1;
    System.out.println("Before the loop");

    while(x < 4) {
        x = x + 1;
        System.out.println("In the loop");
        System.out.println("Value of loop x is " + x);
    }

    System.out.println("This is after the loop");

}

这里的输出是

Before the loop
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
In the loop
Value of loop x is 4
This is after the loop

当我这样改变语句的位置时,

    public static void main (String[] args) {

    int x = 1;
    System.out.println("Before the loop");

    while(x < 4) {
        System.out.println("In the loop");
        System.out.println("Value of loop x is " + x);
        x = x + 1;
    }

    System.out.println("This is after the loop");

}

输出是,

Before the loop
In the loop
Value of loop x is 1
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
This is after the loop

请向我解释为什么仅通过更改该语句的位置,输出就会发生如此巨大的变化。

任何帮助将不胜感激......我是一个目标很高的学习者;)

【问题讨论】:

  • 您正在打印 x 的值,因此在 println 语句之前或之后增加 x 的值会有所不同。

标签: java loops while-loop conditional statements


【解决方案1】:

你基本上有这个:

x = 1
x = x + 1 // X=2
print x   // X=2
--> and then to next loop

x = 1
print x    // X=1 
x = x + 1  // X=2
--> and then to next loop

所以,这真的不是太大的变化,它是对值的 +1,因为你在打印之前而不是在打印之后这样做

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2019-12-20
    • 2021-03-06
    • 2021-12-20
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多