【发布时间】:2020-11-25 08:21:13
【问题描述】:
目前,我有 3 个类:Weapon.java、Warrior.java 和 Game.java。我正在尝试从 Weapon.java 访问打击方法。我假设我必须调用类,然后调用罢工方法,但不知道该怎么做。
public class Weapon {
// Part 1 of ICE16
// 3 properties: String type, int power, and String strikeMessage
private String type = "";
private int power;
private String strikeMessage;
// In class Weapon, create a constructor that assigns values to each of these internal private properties of the class in the order above.
public Weapon (String type, int power, String strikeMessage) {
this.type = type;
this.power = power;
this.strikeMessage = strikeMessage;
}
// Method 1
public int getPower() {
return power;
}
// Method 2
public void strike() {
System.out.println("Weapon of type " + type + " has power " + power);
System.out.println(strikeMessage);
}
// Method 3
public void setPower(int power) {
this.power = power;
}
}
public class Warrior {
// Part 2 of ICE16
// 4 properties: int age, String name, int expLevel, Weapon weapon
private int age = 0;
private String name = "";
private int expLevel = 0;
private Weapon weapon;
// Create a constructor that assigns each value to the property
public Warrior(int age, String name, int expLevel, Weapon weapon) {
this.age = age;
this.name = name;
this.expLevel = expLevel;
this.weapon = weapon;
}
// Method 1
public void attack() {
System.out.println("Warrior, " + name + " with experience level " + expLevel + "attacks!");
}
// Call strike method from Weapon.java
// Method 2
public void assignWeapon(Weapon weapon) {
this.weapon = weapon;
}
【问题讨论】:
-
我不知道你想在攻击期间用你的武器攻击,所以,在attack()方法中,尝试添加this.weapon.strike()