Java Case/switch语句产生重复的结果
所以我有两个case/switch语句,出于某种原因,被这两个变量激活的print语句被激活了两次。我一遍又一遍地阅读代码,没有找到任何会导致打印语句重复的内容。输出为: 黑暗骑士用他的狡猾和意志力再次击败敌人。Java Case/switch语句产生重复的结果,java,switch-statement,Java,Switch Statement,所以我有两个case/switch语句,出于某种原因,被这两个变量激活的print语句被激活了两次。我一遍又一遍地阅读代码,没有找到任何会导致打印语句重复的内容。输出为: 黑暗骑士用他的狡猾和意志力再次击败敌人。 不幸的是,有人带来了氪石:( 黑暗骑士用他的狡猾和意志力再次击败敌人。 不幸的是,有人带来了氪石:( 有人看到错误吗?如果有,请提前感谢您的回答;下面的代码和错误代码用四个引号引起来: class Hero{ String name; int intelligence;
不幸的是,有人带来了氪石:(
黑暗骑士用他的狡猾和意志力再次击败敌人。
不幸的是,有人带来了氪石:( 有人看到错误吗?如果有,请提前感谢您的回答;下面的代码和错误代码用四个引号引起来:
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));
}
}
}
您调用该方法两次,因此出现了双重打印。显示您如何调用该方法。
fight
可能被调用两次。确切地说,显示您的代码。@user2510460您调用的是Hero.fight(超人、蝙蝠侠);
两次。您的主方法未声明为static
。
Hero.fight(Superman, Batman);
System.out.println(Hero.fight(Superman, Batman));