public class AK47 {
public int bullets=100;
public void fire() {
if(bullets==0) {
System.out.println("枪里无子弹");
return;
}
int r=new Random().nextInt(10);
if (r > bullets) {
r=bullets;
}
bullets -=r;
for(int i=0;i<r;i++) {
System.out.print("轰");
}
System.out.println("~");
if(bullets==0) {
System.out.println("弹药已空");
}
}
public void load() {
bullets = 100;
System.out.println("弹夹已满");
}
}
对此代码进行升级,自动装弹
public class AK47
{
private int bullets = 100;
public static void main(String[] args) throws InterruptedException
{
AK47 ak = new AK47();
while (true)
{
if (ak.bullets == 0)
{
System.out.println("弹药已空");
ak.load();
}
ak.fire();
Thread.sleep(200);
}
}
public void fire()
{
int r = new Random().nextInt(10) + 1;
if (r > bullets)
{
r = bullets;
}
bullets -= r;
for (int i = 0; i < r; i++)
{
System.out.print("轰");
}
System.out.println("~");
}
public void load() throws InterruptedException
{
bullets = 100;
System.out.println("正在重新装弹...");
Thread.sleep(3000);
}
}
public class AK47 {
public int bullets=100;
public void fire() {
if(bullets==0) {
load();
System.out.println("枪里无子弹");
return;
}
int r=new Random().nextInt(10);
if (r > bullets) {
r=bullets;
}
bullets -=r;
for(int i=0;i<r;i++) {
System.out.print("轰");
}
System.out.println("~");
if(bullets==0) {
System.out.println("弹药已空");
}
}
public void load() {
bullets = 100;
System.out.println("弹夹已满");
}
public static void main(String[] args) {
AK47 ak47 = new AK47();
for (int i = 0; i < 100; i++) {
ak47.fire();
}
}