开发者

while (var != var) [duplicate]

This question already has 开发者_运维知识库answers here: Closed 12 years ago.

while (var != var) System.out.println(" loop.. ");

execute it.. how to declare..var


Assuming that this is homework, I'll give you a hint, not the answer. You need to define var like this:

double var = // time for you to understand floating point

Edit: to make this answer more generally useful, here's Wikipedia's entry on special floating-point values.


public static void main(String[] args) {
    double var = Double.NaN;
    System.out.println("var : " + var);
    while (var != var) {
        System.out.println(" I am inside loop now! ");
    }

}


double var = Double.NaN


In addition, the following will result in an indefinite loop, rather than an infinite loop; but if there was more stuff going on in the main while loop, [I reckon] this could tip-over to be effectively infinite; thought it was worth posting as this is the type of thing that can happen on App Servers in real-life:

public class Puzzle extends Thread {
static boolean keepRunning=true;
static int var=0;



public void run() {

while (keepRunning) {
        var++;
}   

}


public static void main(String[] args) {
    Puzzle p=new Puzzle();
    p.setPriority(Thread.MAX_PRIORITY);
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    p.start();
    System.out.println("Background Thread started");
    try { Thread.sleep(1000); } catch(Exception e) { ; } // Dirty hack to give the background thread chance to start :)
    while (var != var) {
        System.out.println(" I am inside loop now! ");
    }

    keepRunning=false; // we escaped from the loop, switch off the background thread.
}

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜