class Pistol {
public Magazine magazine;
public void setMagazine(Magazine m) {
this.magazine = m;
System.out.println("setMagazine ");
}
public boolean shoot() {
if (magazine.count > 0) {
magazine.popBullet();
System.out.println("Shooting bullet: " + magazine.bullets[magazine.count ].id);
return true;
} else {
System.out.println("The magazine is empty!");
return false;
}
}
}
class Magazine {
private int capacity = 6;
Bullet[] bullets = new Bullet[capacity];
int count = 0;
public boolean pushBullet(Bullet b) {
if (count < capacity) {
bullets[count++] = b;
return true;
} else {
System.out.println("The magazine is full!");
return false;
}
}
public boolean popBullet() {
if (count > 0) {
Bullet b = bullets[--count];
System.out.println("Popped bullet: " + b.id);
return true;
} else {
System.out.println("The magazine is empty!");
return false;
}
}
public boolean setFull() {
for (int i = count; i < 6; i++) {
Bullet Bn = new Bullet(i);
Bn.id = i+1;//修改前:Bn.id=i;修改后能从1输出。
pushBullet(Bn);
}
System.out.println("setFull");
return true;
}
}
class Bullet {
int id;
public Bullet(int id) {
this.id = id;
}
}
class Mian {
public static void main(String[] args) {
Magazine magazine1 = new Magazine();
Magazine magazine2 = new Magazine();
magazine1.setFull();
magazine2.setFull();
Pistol pistol = new Pistol();
pistol.setMagazine(magazine1);
while (pistol.shoot()) {
}
pistol.setMagazine(magazine2);
while (pistol.shoot()) {
}
}
}
可以运行,但是有两个问题需要解决。
"C:\Program Files\Java\jdk-20\bin\java.exe" "-javaagent:D:\软件\IntelliJ IDEA Community Edition 2023.2.3\lib\idea_rt.jar=12432:D:\软件\IntelliJ IDEA Community Edition 2023.2.3\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath C:\Users\DELL\IdeaProjects\Pistol\out\production\Pistol Mian
setFull
setFull
setMagazine
Popped bullet: 5
Shooting bullet: 5
Popped bullet: 4
Shooting bullet: 4
Popped bullet: 3
Shooting bullet: 3
Popped bullet: 2
Shooting bullet: 2
Popped bullet: 1
Shooting bullet: 1
Popped bullet: 0
Shooting bullet: 0
The magazine is empty!
setMagazine
Popped bullet: 5
Shooting bullet: 5
Popped bullet: 4
Shooting bullet: 4
Popped bullet: 3
Shooting bullet: 3
Popped bullet: 2
Shooting bullet: 2
Popped bullet: 1
Shooting bullet: 1
Popped bullet: 0
Shooting bullet: 0
The magazine is empty!
Process finished with exit code 0
一个是,如何使得id不归零,即magazine2的bullet id 是7-12;
第二个是,如何让id由1开始计算。修改了一处,见注释。
另外还有一个想法,子弹先入后出是不是可以用到栈。或者如何用链表实现(课上提过)
晚安世界