本文介绍了意外的循环无尽的字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(byte i = 0; i  System.out.println(i + 1 ++ name); 


$


当执行我的程序时,它将所有数字从-128打印到127无限循环。为什么会发生这种情况?

解决方案

byte是1个字节的类型,所以可以在-128 ... 127之间变化,我< 128总是如此。当你添加1到127时,它会溢出,在(无限)循环中变成-128,等等...


I have the following loop:

for (byte i = 0 ; i < 128; i++) {
    System.out.println(i + 1 + " " + name);
}

When I execute my programm it prints all numbers from -128 to 127 in an infinite loop. Why does this happen?

解决方案

byte is a 1-byte type so can vary between -128...127, so condition i < 128 is always true. When you add 1 to 127 it overflows and becomes -128 and so on in a (infinite) loop...

这篇关于意外的循环无尽的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 21:25