Case / switch语句产生重复的结果

时间:2014-02-03 01:24:40

标签: java switch-statement

所以我有两个case / switch语句,由于某种原因,两个变量激活的print语句被激活两次。我一遍又一遍地阅读代码,找不到任何会导致重复打印语句的内容。输出是:

  

黑暗骑士利用他的狡猾和意志力再次击败敌人   不幸的是,有人带来了Kryptonite :(
  黑暗骑士用他的狡猾和意志力再次击败敌人   不幸的是,有人带来了Kryptonite :(

有人看到错误吗?如果是这样,请提前感谢任何答案;下面的代码和错误的代码是四重引号:

class Hero{
    String name;
    int intelligence;
    boolean parents;
    double strength;

    public static String fight(Hero hero1, Hero hero2){
    if(hero1.intelligence+hero1.strength>hero2.intelligence+hero2.strength)
        return(hero1.name+" is the winner");
    else{

        //If hero2 wins, initiate this code


    """"switch (hero2.name){
                                    //If the hero's name is ___ then print ____
                case "Batman":
                    System.out.println("The Dark Knight uses his cunning and strength of will to beat down the enemy once again.");
                    break;
                case "Superman":
                    System.out.println("Superman is literally invincible. The Son of Krypton wins again!");
                    break;
                default:
                    break;
                    }
            switch (hero1.name){

                case "Batman":
                    System.out.println("The Dark Knight trudges back to his cave");
                    break;
                case "Superman":
                    System.out.println("Unfortunately, somebody brought Kryptonite :(");
                default:
                    break;
                }""""
        return(hero2.name+" is the winner");

    }
}

class HeroMain{
    public void main(String[] args){
    Hero Superman = new Hero();
    Superman.name = "Superman";
    Superman.intelligence = 7;
    Superman.parents = false;

    Hero Batman = new Hero();
    Batman.name = "Batman";
    Batman.intelligence = 8;
    Batman.parents = false;

    Hero.fight(Superman, Batman);
    System.out.println(Hero.fight(Superman, Batman));
    }
}
}

1 个答案:

答案 0 :(得分:6)

Hero.fight(Superman, Batman);
System.out.println(Hero.fight(Superman, Batman));

您正在调用该方法两次,因此进行双重打印。