偶然发现java一个奇怪的现象
程序一:这个再简单不过了。关键看程序二
public class temp1{
public static void main(String [] args){
int a = 1 ;
System.out.println( "a = "+a);
while(a <200){
a = a * 2;
System.out.println( "a = "+a);
}
}
}
输出结果:
a = 1
a = 2
a = 4
a = 8
a = 16
a = 32
a = 64
a = 128
a = 256
程序二:在程序一的基础上稍作改进while不停地循环
public class temp2{
public static void main(String [] args){
int a = 1 ;
System.out.println( "a = "+a);
while(true){
a = a * 2;
System.out.println( "a = "+a);
}
}
}
输出的结果:一直是a = 0
a = 0
a = 0
a = 0
a = 0
a = 0
a = 0
....
不是我所预期的,请高手解释一下为什么不是
a = 1
a = 2
a = 3
....
------解决方案--------------------笨,很快输出了一大堆,由于输入太多,前面的就没了,
然后就全是0了,因为乘以2相当于左移啊
无聊为什么写这种死循环
------解决方案--------------------这个问题的原因是因为这是个死循环,而且输出太快,你看不到,实际上输出结果是:
a = 1
a = 2
a = 4
a = 8
a = 16
a = 32
a = 64
a = 128
a = 256
a = 512
a = 1024
a = 2048
a = 4096
a = 8192
a = 16384
a = 32768
a = 65536
a = 131072
a = 262144
a = 524288
a = 1048576
a = 2097152
a = 4194304
a = 8388608
a = 16777216
a = 33554432
a = 67108864
a = 134217728
a = 268435456
a = 536870912
a = 1073741824
a = -2147483648
a = 0
a = 0
a = 0
……
你可以在输出语句前加上以下语句:
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
------解决方案--------------------