Stackoverflow上关于if-else语句的有趣问题

来源:互联网 发布:辐射4优化驱动 编辑:程序博客网 时间:2024/05/16 19:30

原文链接为:http://stackoverflow.com/questions/19416644/challenge-in-if-statement-condition?newsletter=1&nlcode=220469%7c2420

Stackoverflow上有码友被人问到,如下程序结构,不改变if-else语句,如何输出Not OK。

class Condition {    // you can change in the main    public static void main(String[] args) {         int x = 0;        if (x == x) {            System.out.println("Ok");        } else {            System.out.println("Not ok");        }    }}

各位码友纷纷支招,比较有意思的有三种。

方式一:利用Float.NaN 或Double.NaN的数值不可比较性。

public class IfStateNaN {public static void main(String[] args) {float x = Float.NaN;if (x == x) {    System.out.println("Ok");} else {    System.out.println("Not ok");}}}

方式二:利用多线程读取一个值和判断这个值的非原子性(从堆空间上取到线程栈空间后,才能执行栈指令进行比较,两次取数之前可被其他线程修改掉)。

该方式在Windows开发机器上,只在程序运行开始阶段偶尔会出现,后面运行就不出现了,估计被JVM优化了,直接从方法区空间取值,省略了取到栈空间的步骤。

public class IfStateThread {static int x = 0;public static void main(String[] args) {Thread thread = new Thread(){public void run(){while(true) x++;}};thread.start();while(true){if (x == x) {    //System.out.println("Ok");} else {    System.out.println("Not ok");}}}}

也有重载System.out.println方法,直接修改输出的。

public class IfStateStream extends PrintStream{    public IfStateStream(PrintStream x) {super(x);}    public void println(String x) {super.println("Not ok");}    public static void main(String[] args) {        System.setOut(new IfStateStream(System.out));        int x = 0;        if (x == x) {            System.out.println("Ok");        } else {            System.out.println("Not ok");        }    }}

如果是C++,还可以将 x封装成对象,将 == 运算符重载,将原来相等的运算结果返回不相等的运算结果。




原创粉丝点击