JAVA定义父类Role,定义属性name, 两个子类Soldier和Magicer 定义父类武器Weapon, 定义属性name, 方法attack()攻击 三个子类Sword,Knife,Mace(狼牙棒), 其中 Sword的attack伤害值为100 Knife的attack伤害值为200 Mace的attack伤害值为300 其中战士Soldier和法师Magicer可以使用任意一种武器 从控制台输入指令 1>输入A,创建Soldier 2>输入B,创建Magicer 3>输入1,创建Sword 4>输入2,创建Knife 5>输入3,创建Mace 当战士和法师满5个时,而且每个角色配备自己选择的武器, 组队去攻击,求攻击总值
时间: 2023-04-03 07:02:57 浏览: 101
KeyGenerator_java_soldier6n8_KeyGenerator_
好的,根据您的描述,我可以回答这个问题。根据题目要求,我们可以定义以下类和属性:
```
class Role {
String name;
}
class Soldier extends Role {
Weapon weapon;
}
class Magicer extends Role {
Weapon weapon;
}
class Weapon {
String name;
int damage;
void attack() {
System.out.println("使用" + name + "攻击,造成" + damage + "点伤害");
}
}
class Sword extends Weapon {
public Sword() {
name = "剑";
damage = 100;
}
}
class Knife extends Weapon {
public Knife() {
name = "刀";
damage = 200;
}
}
class Mace extends Weapon {
public Mace() {
name = "狼牙棒";
damage = 300;
}
}
```
接下来,我们可以编写一个控制台程序来创建角色和武器,并计算攻击总值:
```
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Soldier> soldiers = new ArrayList<>();
List<Magicer> magicers = new ArrayList<>();
List<Weapon> weapons = new ArrayList<>();
while (true) {
System.out.println("请输入指令:");
System.out.println("A. 创建战士");
System.out.println("B. 创建法师");
System.out.println("1. 创建剑");
System.out.println("2. 创建刀");
System.out.println("3. 创建狼牙棒");
String command = scanner.nextLine();
if (command.equals("A")) {
if (soldiers.size() >= 5) {
System.out.println("战士已满,请选择其他角色");
continue;
}
Soldier soldier = new Soldier();
System.out.println("请输入战士的名字:");
soldier.name = scanner.nextLine();
soldiers.add(soldier);
} else if (command.equals("B")) {
if (magicers.size() >= 5) {
System.out.println("法师已满,请选择其他角色");
continue;
}
Magicer magicer = new Magicer();
System.out.println("请输入法师的名字:");
magicer.name = scanner.nextLine();
magicers.add(magicer);
} else if (command.equals("1")) {
Sword sword = new Sword();
weapons.add(sword);
} else if (command.equals("2")) {
Knife knife = new Knife();
weapons.add(knife);
} else if (command.equals("3")) {
Mace mace = new Mace();
weapons.add(mace);
} else {
System.out.println("无效的指令,请重新输入");
}
if (soldiers.size() >= 5 && magicers.size() >= 5 && weapons.size() >= 10) {
int totalDamage = 0;
for (Soldier soldier : soldiers) {
Weapon weapon = weapons.get(0);
soldier.weapon = weapon;
weapons.remove(0);
totalDamage += weapon.damage;
}
for (Magicer magicer : magicers) {
Weapon weapon = weapons.get(0);
magicer.weapon = weapon;
weapons.remove(0);
totalDamage += weapon.damage;
}
System.out.println("组队成功,攻击总值为:" + totalDamage);
break;
}
}
}
}
```
这个程序可以让用户输入指令来创建角色和武器,当战士和法师满5个,并且每个角色都配备了自己选择的武器时,程序会计算攻击总值并输出。
阅读全文