首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

解决JAVA switch case 里面case A, A不能为 变量的有关问题

2012-10-28 
解决JAVA switch case 里面case A, A不能为 变量的问题今天有个朋友问我Java switch case里面的用法,由于

解决JAVA switch case 里面case A, A不能为 变量的问题

今天有个朋友问我Java switch case里面的用法,由于 switch case 和 if-else 工作原理不一样,可能某些公司会避免使用if-else而采用switch case的方法来解决问题。

在jdk1.6 中:

int i= "test".hashcode();

String s = "test";

switch (s.hashcode()) {

? case i :System.out.println("bad");

}//这种方法是不支持的。编译根本通过不了,因为 i 是一个变量

?

经过网上一翻查找,在jdk1.7中可能会支持这个功能。

但是问题就不能这么简单的解决,因为现在很多企业都没有在使用1.7的版本。

没事在电脑面前想出来一个办法,应该可以行得通在jdk1.6中解决 case不能使用变量的方法

上代码

public class TestHash {

?/**
? * Comments:
? * @author Jacky
? * Chinese :
? * @param args
? */
?public static void main(String[] args) {
??

?? String s = "test";

?

?? int i= "test".hashCode();

?

??switch ( ("test1".hashCode()== i ? 1:1)?*("test2".hashCode() == i ? 2:1) *(s.hashCode() == i ? 3 :1) ){


???????????? case?? 1 :System.out.println("not good");break;


???????????? case?? 2 : System.out.println("not good"); break;


??????????? ?case?? 3? : System.out.println("good"); break;

?

???????????? default : System.out.print(4); break;


??}//switch


?}// main

?

}//class

?

ok,我运行了下,运行结果是打印 good

看来这样是行得通的,而且也避免了case后面使用变量;但是效率应该还算行吧。比If-else应该好一点。

望各位大侠指点。

还有一种办法,枚举类型也可以行得通!

热点排行