Java Programming: Create two classes: Alien: An Alien has an int health and an i
ID: 663437 • Letter: J
Question
Java Programming:
Create two classes:
Alien: An Alien has an int health and an int damage (reflecting it's own health and the damage it does to other aliens).
Constructors:
Alien(int, int): sets both values. Assume for now that the values are valid.
Alien(Alien): Creates a copy of the Alien passed in.
Methods:
Boolean isAlive(): True of health > 0, false otherwise
void takeDamage(int): reduce health by argument amount
int getDamage(): return damage value
int getHealth(): return health value
toString()
Second class:
Alien Pack:
Contains an array of alien references and an int indicating the next open location in the array.
Constructors:
AlienPack(int): creates the array with the specified size. No Aliens are created here.
AlienPack(AlienPack): Creates the array as a copy of the array in the alienPack passed in. This is tricky, and you don't have to get it totally right. This constructor should be deep copied.
Methods:
void addAlien(Alien): adds an alien to the pack (puts it in the array) if there is a spot in the array. Otherwise do nothing. This alien is added without deep copying.
int getTotalDamage(): returns the total damage the pack can cause.
Explanation / Answer
// Alien.java
public class Alien{
int health;
int damage;
Alien(int h, int d){
health = h;
damage = d;
}
Alien(Alien a){
this.health = a.health;
this.damage = a.damage;
}
boolean isAlive(){
if(health > 0) return true;
else return false;
}
void takeDamage(int d){
damage -= d;
}
int getDamage(){
return damage;
}
int getHealth(){
return health;
}
public String toString(){
return "Health: " + health + ", damage: " + damage;
}
}
// AlienPack.java
public class AlienPack{
Alien array[];
int next;
AlienPack(int size){
array = new Alien[size];
}
AlienPack(AlienPack a){
this.array = a.array;
this.next = a.next;
}
void addAlien(Alien a){
if(next < array.length){
array[next] = a;
}
}
int getTotalDamage(){
int total = 0;
for(int i = 0; i < next; i++){
total += array[i].damage;
}
return total;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.