锁定老帖子 主题:奇怪的 switch() case 题目
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
|
|
---|---|
作者 | 正文 |
发表时间:2009-03-13
如果想对任何输入的数字都好用也不需要嵌套那么复杂了,以下这样就可以啊!
int x = 10; x=(x<1)?0:x; switch (x) { case 0: System.out.println("x is less than 1"); break; case 1: System.out.println("x is 1"); break; case 2: case 3: case 4: System.out.println("x is 2,3,4"); break; default: System.out.println("x is greater than 4"); } 另外欢迎大家我访问我的个人博客:bradoo.cn |
|
返回顶楼 | |
发表时间:2009-03-13
凑凑热闹,我这样写的
switch(x>4?5:(x<1?0:x)){ case 0:System.out.println("x小于1"); break; case 1:System.out.println("x=1"); break; case 2: case 3: case 4:System.out.println("x是2,3,4"); break; case 5:System.out.println("x大于4"); break; } |
|
返回顶楼 | |
发表时间:2009-03-14
呵呵 你们都真聪明啊
|
|
返回顶楼 | |
发表时间:2009-03-14
这时候脑子乱了,短的还挺好读懂,但判断次数是不是多了。
|
|
返回顶楼 | |
发表时间:2009-03-16
gufenglian 写道 凑凑热闹,我这样写的
switch(x>4?5:(x<1?0:x)){ case 0:System.out.println("x小于1"); break; case 1:System.out.println("x=1"); break; case 2: case 3: case 4:System.out.println("x是2,3,4"); break; case 5:System.out.println("x大于4"); break; } 好像最简洁咯 |
|
返回顶楼 | |
发表时间:2009-03-16
最后修改:2009-03-16
都不对,题目很明显只让用switch 而不能用其他的判断比如if\3元表达式(for 和while应该也不算)
看看这个怎么样: public class Switch { public static void main(String[] args) { int x =5; try { switch ((x-1)/x) { case 1: case 2: System.out.println("x is less than 1"); break; default: switch ((x+4)/x) { case 5: System.out.println("x is 1"); break; case 3: case 2: System.out.println("x is 2,3,4"); break; case 1: System.out.println("x is greater than 4"); break; } break; } } catch (Exception e) { System.out.println("x is less than 1"); } } } |
|
返回顶楼 | |
发表时间:2009-03-16
int x = 5;
int y = x < 1 ? -1 : x == 1 ? 1 : x == 2 || x == 3 || x == 4 ? 2 : x > 4 ? 5 : 0; switch (y) { case 0: System.out.println("非法数字........"); break; // case int x<1: case -1: System.out.println("x is less than 1"); break; // case x==1: case 1: System.out.println("x is 1"); break; // case x<=4: case 2: System.out.println("x is 2,3,4"); break; case 5: System.out.println("x is greater than 4"); break; } |
|
返回顶楼 | |
发表时间:2009-03-17
不要为了简洁而搞得晦涩难懂,不值得
|
|
返回顶楼 | |
发表时间:2009-03-19
最后修改:2009-03-19
bravewu 写道
需要那么复杂吗?我这样就行啊!
int x = 5; switch (x) { case 1: System.out.println("x is 1"); break; case 2: case 3: case 4: System.out.println("x is 2,3,4"); break; case 5: System.out.println("x is greater than 4"); break; default: System.out.println("x is less than 1"); }
|
|
返回顶楼 | |
发表时间:2009-03-19
应该考虑0的吧
public static void testCase(int x) { switch (x) { case 1: System.out.println("is 1"); break; case 2: case 3: case 4: System.out.println("is 2 3 4"); break; default: x = x > 4 ? 5 : -1; case 5: System.out.println("big 4"); break; case 0: case -1: System.out.println("less 1"); } } |
|
返回顶楼 | |