Attack类(父类):
public class Attack {
private String name ;
private int hp;
private int atk;
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
public void setHp(int h){
hp = h;
}
public int getHp(){
return hp;
}
public void setAtk(int a){
atk = a;
}
public int getAtk(){
return atk;
}
}
monster类(子类):
public class monster extends Attack{
public void attacka(ultraman u){
u.setHp(u.getHp() - getAtk());
System.out.println(getName()+"正在攻击"+u.getName()+" "+u.getName() +"掉血"+getAtk()+"剩余血量"+u.getHp());
}
public void attackb(boss b){
b.setHp(b.getHp() - getAtk());
System.out.println(getName()+"正在攻击"+b.getName()+" "+b.getName() +"掉血"+getAtk()+"剩余血量"+b.getHp());
}
}
ultraman 类(子类):
public class ultraman extends Attack {
public void attackm(monster m){
m.setHp(m.getHp() - getAtk());
System.out.println(getName()+"正在攻击"+m.getName()+" "+m.getName() +"掉血"+getAtk()+"剩余血量"+m.getHp());
}
public void attackb(boss b){
b.setHp(b.getHp() - getAtk());
System.out.println(getName()+"正在攻击"+b.getName()+" "+b.getName() +"掉血"+getAtk()+"剩余血量"+b.getHp());
}
}
manage类:
public class Manage {
public static void main(String[] args) {
monster mo = new monster();
mo.setName("小怪兽");
mo.setHp(120);
mo.setAtk(10);
ultraman ul = new ultraman();
ul.setName("奥特曼");
ul.setHp(100);
ul.setAtk(15);
boss bo = new boss();
bo.setName("boss");
bo.setHp(200);
bo.setAtk(20);
int w = 0;
for (;;) {
// 实参是对象名(通过对象名调用类)
mo.attacka(ul);
if (ul.getHp() <= 0) {
System.out.println("小怪兽赢");
w = 1;
break;
}
ul.attackm(mo);
if (mo.getHp() <= 0) {
System.out.println("奥特曼赢");
w = 2;
break;
}
}
if (w == 1) {
mo.setHp(120);
while (true) {
mo.attackb(bo);
if (bo.getHp() <= 0) {
System.out.println("小怪兽赢");
break;
}
bo.attackm(mo);
if (mo.getHp() <= 0) {
System.out.println("boss赢");
break;
}
}
}
if (w == 2) {
ul.setHp(100);
while (true) {//while(true){}与for(;;){}一样都是死循环;
ul.attackb(bo);
if (bo.getHp() <= 0) {
System.out.println("奥特曼赢");
break;
}
bo.attacka(ul);
if (ul.getHp() <= 0) {
System.out.println("boss赢");
break;
}
}
}
}
}
最后输出的结果如下图片所示