下面是用 Java 代码模拟一个人开枪射击的过程的示例:

class Gun {
    private int[] bulletClip;
    private int capacity;
    private int bulletCount;

    public Gun() {
        capacity = 5;
        bulletClip = new int[capacity];
        bulletCount = 0;
    }

    public void push(int bullet) {
        if (bulletCount < capacity) {
            bulletClip[bulletCount] = bullet;
            bulletCount++;
            System.out.println("装填子弹:" + bullet);
        } else {
            System.out.println("弹夹已满,无法再装填子弹");
        }
    }

    public void pop() {
        if (bulletCount > 0) {
            int bullet = bulletClip[0];
            for (int i = 0; i < bulletCount - 1; i++) {
                bulletClip[i] = bulletClip[i + 1];
            }
            bulletCount--;
            System.out.println("打出子弹:" + bullet);
        } else {
            System.out.println("弹夹中没有子弹");
        }
    }
}

class Person {
    public void shoot(Gun gun) {
        if (gun != null) {
            gun.pop();
        } else {
            System.out.println("没有枪支");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Gun gun = new Gun();
        Person person = new Person();

        gun.push(1);
        gun.push(2);
        gun.push(3);

        person.shoot(gun);
        person.shoot(gun);
        person.shoot(gun);

        gun.push(4);
        gun.push(5);

        person.shoot(gun);
        person.shoot(gun);
    }
}

输出结果为:

装填子弹:1
装填子弹:2
装填子弹:3
打出子弹:1
打出子弹:2
打出子弹:3
装填子弹:4
装填子弹:5
打出子弹:4
打出子弹:5

注:以上代码只是一个简单的示例,可能并不符合实际情况,例如没有考虑到子弹数量超过弹夹容量的情况,也没有考虑到多人同时开枪的情况。实际应用中需要根据具体需求进行相应的修改和扩展


原文地址: https://www.cveoy.top/t/topic/ickF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录