给房子添加家居:
// 家居类
public class HouseItem {
public String name;
public double area;
// 构造方法
public HouseItem(String name, double area) {
this.name = name;
this.area = area;
}
}
// 房子类
public class House {
public String houseType;
public double area;
public double freeArea;
public String[] houseItem = new String[10];
// 添加家居
public void insert(HouseItem houseItem) {
// 判断数组是否还有容量
int insertIndex = -1;
for (int i = 0; i < this.houseItem.length; i++) {
if (this.houseItem[i] == null) {
insertIndex = i;
break;
}
}
if (insertIndex == -1) {
System.out.println("家里容纳不下这个这个" + houseItem.name);
return;
}
// 判断家里面积是否够用
if (houseItem.area > freeArea) {
System.out.println("家里没这么大地方,容纳不下这个" + houseItem.name);
return;
}
// 算出剩余面积
freeArea -= houseItem.area;
// 输出成功添加哪个家居
this.houseItem[insertIndex] = houseItem.name;
System.out.printf("%s添加成功!\n", this.houseItem[insertIndex]);
}
// 输出信息
public void showInfo() {
System.out.println("户型是:" + houseType);
System.out.println("总面积是:" + area);
System.out.println("剩余面积是:" + freeArea);
System.out.println("家居列表如下:");
for (String item : houseItem) {
if (item != null) {
System.out.println(item);
}
}
}
// 构造方法
public House(String houseType, double area) {
this.houseType = houseType;
this.area = area;
this.freeArea = area;
}
}
// 测试类
public static void main(String[] args) {
HouseItem bed = new HouseItem("席梦思",4);
HouseItem bed = new HouseItem("衣柜",2);
HouseItem bed = new HouseItem("餐桌",1.5);
House house = new House("一室一厅",19);
house.insert(bed);
house.insert(bed);
house.insert(table);
house.insert(bed);
house.insert(chest);
house.showInfo();
house.insert(bed);
}
士兵发射子弹:
// 枪类
public class Gun {
public String model;
public int bulletCount;
// 添加子弹
public void addBullet() {
bulletCount += 10;
System.out.println(model + "正在装弹,现在子弹数为:" + bulletCount);
}
// 发射子弹
public void shoot() {
bulletCount --;
System.out.printf("%s正在发射子弹,子弹数量为:%d\n", model, bulletCount);
}
// 构造方法
public Gun(String model, int bulletCount) {
this.model = model;
this.bulletCount = bulletCount;
}
}
// 士兵类
public class Soldier {
public String name;
public Gun gun;
// 开火
public void fire() {
System.out.printf("%s正在拿着一把%s开火!\n", name, gun.model);
int i = 1;
while (true) {
if (gun.bulletCount == 0) {
gun.addBullet();
}
gun.shoot();
i ++;
if (i == 20) {
break;
}
}
}
// 构造方法
public Soldier() {
this.name = name;
this.gun = gun;
}
}
// 测试类
public static void main(String[] args) {
Gun gun = new Gun("AK47", 15);
Soldier soldier = new Soldier("许三多", gun);
soldier.fire();
}