我正在尝试比较两个对象实例
一个。创建一个名为Cyclops的超级英雄
Superhero Cyclops = new Superhero("Cyclops");
湾创建一个名为Colossus的超级英雄。巨像的力量为40
Superhero Colossus = new SuperHero("Colossus", 40);
名为Cyclops的对象的第一个实例的默认值为10,第二个对象的值已分配为40,这是代码中的强度值。
我如何制定一种考虑到自己的优势并确定获胜者的战斗方法?
超级英雄课程的代码显示在
下面public class Superhero{
//private instance variables declared below
//name of the super hero
private String name;
//name of the strength variable
private int strength;
//The variable for the powerUp method
private int powerUp;
//variable to store the power of the power up
private int storePower;
//getter and setter methods.
public int getStrength(){
return strength;
}
/*
This method takes in an integer paremeter and based on that it does
some calculations.
There are four possible integer values you can pass in: 100, 75, 50 and 25.
If 100 has been passed in the storePower variable is set to 40 which would be
a power-up of 40, if 75 then power-up of 30, if 50 then a power-up of 20,
if 25 then a power-up of 10 and if the right ammount is not specified a power-up
of 0 will be assigned.
*/
public int powerUp(int powerUp){
this.powerUp = powerUp;
if(powerUp == 100){
storePower = 40;
}else if(powerUp == 75){
storePower = 30;
}else if(powerUp == 50){
storePower = 20;
}else if(powerUp == 25){
storePower = 10;
}else{
storePower = 0;
}
strength = strength + storePower;
System.out.println("After receiving a power-up: " + name + " has a Strength of: " + strength);
return strength;
}
public void fight(){
}
//constructor for if the player wanted to specify the name and the strength
public Superhero(String name, int strength){
this.name = name;
this.strength = strength;
System.out.println(name + " " + strength);
}
//if the user doesn't enter the strength as it is optional
//this constructor below will run and set the default
public Superhero(String name){
this.name = name;
strength = 10;
System.out.println(name + " " + strength );
}
}
正如你所看到的那样,公开无效的斗争是空的,因为这是我想要创造的方法。
战斗类的主要方法也显示在下面
public class Fight{
public static void main(String[] args){
// a. Create a Superhero named Cyclops
Superhero Cyclops = new Superhero("Cyclops");
//b. Create a Superhero named Colossus. Colossus has a strength of 40
Superhero Colossus = new SuperHero("Colossus", 40);
Cyclops.fight(Cyclops.getStrength(), Colossus.getStrength());
//d. Give Cyclops a powerUp of 100
Cyclops.powerUp(100);
}
}
答案 0 :(得分:2)
您可以像其他方法一样通过参数传递英雄,并返回战斗的胜利者:
public SuperHero fight(SuperHero opponent) {
if (this.getStrength() > opponent.getStrength())
return this
return opponent;
}
所以你可以接到主要电话:
SuperHero winner = cyclope.fight(colossus);
System.out.println("The winner is: " + winner);
此问题可帮助您了解如何考虑问题。你在这里有一个SuperHero课程,你想让SuperHeros战斗,如你所知,一场战斗有一个胜利者,所以功能的回归可以成为战斗的胜利者。在类主体上,您正在创建通过this
关键字\变量访问的实例的行为,因此您只需要this
英雄将与之对抗的对手,创建SuperHero opponent
参数是一个好方法。比较强度值,你找到胜利者并返回它。您可以改进并添加更多属性进行比较,同时,在SuperHeros具有相同强度时定义行为,如果您可以随机选择则会很好。
还有一个建议,看看我的变量的名称,它们以小写字母开头,它是Java惯例,您应该关心它,它可以帮助您阅读代码。