import java.util.HashMap;
import java.util.Scanner;
//Tank.java
class Tank {
// 声明double型变量speed,刻画速度
private double speed;
// 声明int型变量bulletAmount,刻画炮弹数量
private int bulletAmount=10;
private int id;
private boolean started = false;
public Tank(int id) {
this.id = id;
}
public int getid() {
return id;
}
public void start() {
started = true;
}
void speedUp() {
if (started && speed < 90) {
speed += 15;
}
else
System.out.println("坦克未启动");
}
void speedDown() {
if (started && speed > 0) {
speed -= 15;
}
else
System.out.println("坦克未启动");
}
void setBulletAmount(int m) {
bulletAmount = m;
}
int getBulletAmount() {
return bulletAmount;
}
double getSpeed() {
return speed;
}
void fire() {
if (started ) {
if(bulletAmount >= 1){
// 将bulletAmount - 1赋值给bulletAmount
bulletAmount--;
System.out.println("打出一发炮弹");
}
else {
System.out.println("没有炮弹了,无法开火");
}
}
else
System.out.println("坦克未启动,无法开火");
}
void stop() {
if (started) {
System.out.println("该坦克停车了");
speed = 0;
started=false;
}
else
System.out.println("坦克未启动");
}
}
//Fight.java
@FunctionalInterface
interface TankOpe {
void operate(Tank tank);
}
public class Fight {
public static void main(String args[]) {
HashMap<String, Tank> tanks = new HashMap<>();
HashMap<String, TankOpe> operations = new HashMap<>();
Tank tank1 = new Tank(1);
Tank tank2 = new Tank(2);
tanks.put("1", tank1);
tanks.put("2", tank2);
operations.put("start", Tank::start);
operations.put("speedUp", Tank::speedUp);
operations.put("speedDown", Tank::speedDown);
operations.put("fire", Tank::fire);
operations.put("stop", Tank::stop);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入坦克编号(1或2),0退出:");
int tankNum = scanner.nextInt();
if (tankNum == 0) {
break;
}
while (true) {
String tankKey = String.valueOf(tankNum);
if (!tanks.containsKey(tankKey)) {
System.out.println("无效的坦克编号");
continue;
}
Tank selectedTank = tanks.get(tankKey);
System.out.println("请输入操作编号(1:start; 2:speedUp; 3:speedDown; 4:fire; 5:stop; 0:退出当前坦克操作)");
int opNum = scanner.nextInt();
if (opNum == 0) {
break;
}
String opKey = "";
switch (opNum) {
case 1:
opKey = "start";
break;
case 2:
opKey = "speedUp";
break;
case 3:
opKey = "speedDown";
break;
case 4:
opKey = "fire";
break;
case 5:
opKey = "stop";
break;
default:
System.out.println("无效的操作编号");
continue;
}
TankOpe op = operations.get(opKey);
op.operate(selectedTank);
System.out.println("tank" + tankNum + "的炮弹数量:" + selectedTank.getBulletAmount());
System.out.println("tank" + tankNum + "目前的速度:" + selectedTank.getSpeed());
}
}
scanner.close();
}
}
25万+





