2011-05-23 28 views
3

这里是我的Java代码:预计这个循环是无限的,但它不是

public class Prog1 { 
    public static void main(String[] args) { 
     int x = 5; 
     while (x > 1) { 
      x = x + 1; 
      if (x < 3) 
       System.out.println("small x"); 
     } 
    } 
} 

这是输出:

small x 

我期待一个无限循环..任何想法为什么这样表现?

回答

4

X启动出去5.然后,你遍历它进入6,7,8,等最终它达到了最大可能的整数。下一个x = x + 1将其设置为最负的整数,负值20亿 - 无论如何。这小于3,因此消息被输出。然后再次执行while条件,现在失败,退出循环。

所以虽然它似乎是一个无限循环,但它并不是真的。

这是一个功课问题吗?为什么你会写这样奇怪的代码?

+0

是这是一个家庭作业的问题....谢谢.... – hari 2011-05-23 16:46:24

6

有一个无限循环。就在一段时间内,x变得非常有限,以至于它溢出了signed int的极限,并且变为负值。

public class Prog1 { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     int x = 5; 
     while (x > 1) { 
      x = x + 1; 
      System.out.println(x); 
      if(x < 3) 
       System.out.println("small x"); 
     } 
    } 
} 
1

X溢出了int的极限。通过添加println语句X检查值

public static void main(String[] args) { 
// TODO Auto-generated method stub 
int x = 5; 
while (x > 1) { 
    x = x + 1; 
    if(x < 3){ 
     System.out.println(x); 
     System.out.println("small x"); 
    } 
} 

我的JVM显示x作为-2147483648

1

Java整数被签名,并且它们溢出(如在C和许多其他语言中)。 试试这个检查行为:

public class TestInt { 
    public static void main(String[] args) { 
    int x = Integer.MAX_VALUE; 
    System.out.println(x); 
    x++; 
    System.out.println(x); 
    } 
}