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-05 15:03:40 浏览: 42
可以回答这个问题。以下是代码实现:
```
import java.util.ArrayList;
import java.util.Scanner;
class Role {
String name;
public Role(String name) {
this.name = name;
}
}
class Soldier extends Role {
public Soldier(String name) {
super(name);
}
}
class Magicer extends Role {
public Magicer(String name) {
super(name);
}
}
class Weapon {
String name;
public Weapon(String name) {
this.name = name;
}
public int attack() {
return 0;
}
}
class Sword extends Weapon {
public Sword(String name) {
super(name);
}
public int attack() {
return 100;
}
}
class Knife extends Weapon {
public Knife(String name) {
super(name);
}
public int attack() {
return 200;
}
}
class Mace extends Weapon {
public Mace(String name) {
super(name);
}
public int attack() {
return 300;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Role> roles = new ArrayList<>();
ArrayList<Weapon> weapons = new ArrayList<>();
while (true) {
System.out.println("请输入指令:");
String command = scanner.nextLine();
if (command.equals("A")) {
if (roles.size() >= 5) {
System.out.println("战士已满!");
} else {
System.out.println("请输入战士的名字:");
String name = scanner.nextLine();
roles.add(new Soldier(name));
}
} else if (command.equals("B")) {
if (roles.size() >= 5) {
System.out.println("法师已满!");
} else {
System.out.println("请输入法师的名字:");
String name = scanner.nextLine();
roles.add(new Magicer(name));
}
} else if (command.equals("1")) {
System.out.println("请输入剑的名字:");
String name = scanner.nextLine();
weapons.add(new Sword(name));
} else if (command.equals("2")) {
System.out.println("请输入刀的名字:");
String name = scanner.nextLine();
weapons.add(new Knife(name));
} else if (command.equals("3")) {
System.out.println("请输入狼牙棒的名字:");
String name = scanner.nextLine();
weapons.add(new Mace(name));
} else if (command.equals("attack")) {
if (roles.size() < 5) {
System.out.println("战士或法师不足5个!");
} else if (weapons.size() < 5) {
System.out.println("武器不足5个!");
} else {
int totalAttack = 0;
for (int i = 0; i < 5; i++) {
Role role = roles.get(i);
Weapon weapon = weapons.get(i);
System.out.println(role.name + "使用" + weapon.name + "攻击,造成" + weapon.attack() + "点伤害!");
totalAttack += weapon.attack();
}
System.out.println("攻击总值为:" + totalAttack);
break;
}
} else {
System.out.println("无效指令!");
}
}
}
}
```
运行程序后,按照要求输入指令,最后输入"attack"指令即可得到攻击总值。
阅读全文