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封装成对象,将 == 运算符重载,将原来相等的运算结果返回不相等的运算结果。
- Stackoverflow上关于if-else语句的有趣问题
- stackoverflow 上关于选择 switch 而不是 if / else 的讨论
- StackOverflow上七个有趣的Java问题
- 有趣的if-else
- if else 语句返回的问题
- if else if else 语句的拓展
- 有趣的if语句
- 有趣的if语句
- if---else----一个有趣的题目
- if else 语句 的优化
- 嵌套的if-else语句
- if..else语句的嵌套
- if else语句的应用
- else if 语句的应用
- shell的if else 语句
- angularjs的if、else语句
- if else语句的使用
- ejs 的else if语句,
- 山寨腾讯“爱消除”游戏7日教程
- Maven系列学习(5)-生命周期及插件
- openGL入门小程序
- CI(8) 验证码
- OCP-1Z0-053-V12.02-156题
- Stackoverflow上关于if-else语句的有趣问题
- 【C#】C#新手好用不好找的2个属性设置
- 探索Antlr(Antlr 3.0更新版)
- 听学长学姐聊求职血泪史
- RefBase, sp, wp
- 为什么拥有spinlock的时候不可以sleep
- Rime协议栈概述及学习资料
- android 中checkbox radiobutton文字间间距处理
- Android ProgressBar自定义图片进度,自定义渐变色进度条