switch()的参数只能是整型和布尔型,为什么以下程序在我机器上运行通过,在其他机器上运行错误??
- Java code
class Zuoye1 { public static void main(String[] args) { long str=System.currentTimeMillis(); Magicer m1=new Magicer("甘道夫",55,10,9,"B"); //定义玩家1 m1.practice(); System.out.printf("fire hurt is %d,level is %d,DPS is %d\n",m1.fire(),m1.getLevel(),m1.attack()); m1.practice(); System.out.printf("fire hurt is %d,level is %d,DPS is %d\n",m1.fire(),m1.getLevel(),m1.attack()); m1.practice(); System.out.printf("fire hurt is %d,level is %d,DPS is %d\n",m1.fire(),m1.getLevel(),m1.attack()); long end=System.currentTimeMillis(); System.out.printf("run time:%s",(end-str)); }}interface Role{ public int attack(); //攻击 public void practice(); //练习}abstract class NameRole implements Role //角色名字和年龄{ private String name; private int age; public NameRole(String name,int age){ this.name=name; this.age=age; }}interface MagicStick { public int fire();}class GreenStick implements MagicStick{ private int month; public GreenStick(int month){ this.month=month; } public int fire(){ if(month==6||month==7||month==8) return 2; else return 1; }}class BlackStick implements MagicStick{ private int month; public BlackStick(int month){ this.month=month; } public int fire(){ if(month%2==0) return 2; else return 1; }}class Magicer extends NameRole implements MagicStick{ private String name; private int age; private int level; //魔法值 private int month; //升级月份 private String stick; Magicer(String name,int age,int level,int month,String stick){ super(name,age); this.level=level; this.month=month; this.stick=stick; } public int getLevel(){ return this.level; } public int fire(){ //使用法术 int res=0; //返回值 switch(stick){ case "G":GreenStick s1=new GreenStick(this.month); res=s1.fire(); break; case "B":BlackStick s2=new BlackStick(this.month); res= s2.fire(); break; default:System.out.println("haven't using stick!"); } return res; } public int attack(){ return this.level*5; } public void practice(){ if(this.stick==null) level++; else level+=1+this.fire(); month++; } }
我机器上运行的结果:
其他jdk1.6的都说swith()那里出错,难道是1.7的问题?还是我机器碉堡了??
------解决方案--------------------------------------------------------
不是你机器的问题, 这是JDK1.7的新特性 支持在swicth case使用字符串匹配,1.6以下不支持