看似无休止的循环终止,除非使用System.out.println [英] Seemingly endless loop terminates, unless System.out.println is used

查看:161
本文介绍了看似无休止的循环终止,除非使用System.out.println的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的假定的代码是一个无限循环,因为 x 会一直增长,并且始终保持大于Ĵ

  int x = 5; 
int y = 9;
for(int j = 0; j x = x + y;
}
System.out.println(y);

但是,它会打印 y 和不会无止境地循环。我无法弄清楚为什么。然而,当我以下面的方式调整代码:

  int x = 5; 
int y = 9;
for(int j = 0; j x = x + y;
System.out.println(y);
}
System.out.println(y);

它变成了一个无限循环,我不知道为什么。 java是否认识到它是一个无限循环,在第一种情况下跳过它,但是必须在第二种情况下执行一个方法调用,所以它的行为如预期的那样?
Confused:)

解决方案

这两个例子都不是永无止境的。 $ b

这个问题是Java中的 int 类型的限制(或者几乎任何其他的通用语言)。当 x 的值达到 0x7fffffff 时,添加任何正值将导致溢出, x 变成负值,因此低于 j



第二个循环是,内部代码需要更多的时间,大概需要几分钟,直到 x 溢出。对于第一个例子来说,它可能会少于第二个,或者最有可能的是代码将被优化器删除,因为它没有任何作用。



正如讨论中提到的,时间将很大程度上取决于操作系统如何缓冲输出,是否输出到终端仿真器等,所以它可以比几分钟高得多。

I had a simple bit of code that was supposed to be an endless loop since x will always be growing and will always remain larger than j.

int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
   x = x + y;
}
System.out.println(y);

but as is, it prints y and does not loop endlessly. I cannot figure out why. However, when I adjust the code in the following manner:

int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
    x = x + y;
    System.out.println(y);
}
System.out.println(y);

It becomes an endless loop and I have no idea why. Does java recognize its an endless loop and skip it in the first situation but has to execute a method call in the second so it behaves as expected? Confused :)

解决方案

Both of the examples are not endless.

The issue is the limitation of int type in Java (or pretty much any other common language). When the value of x reaches 0x7fffffff, adding any positive value will result in overflow and the x becomes negative, therefore lower than j.

The difference between the first and second loop is that the inner code takes much more time and it would take probably several minutes until x overflows. For the first example it may take less than second or most probably the code will be removed by optimizer as it doesn't have any effect.

As mentioned in the discussion, the time will heavily depend on how OS buffers the output, whether it outputs to terminal emulator etc., so it can be much higher than few minutes.

这篇关于看似无休止的循环终止,除非使用System.out.println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆