附:TestingMonster代码段
import java.util.*;
public class TestingMonsters {
public static void main(String[] args) {
ArrayList monsters = new ArrayList();
monsters.add(new Monster("Tom"));
monsters.add(new Monster("George"));
monsters.add(new Dragon("Smaug"));
monsters.add(new Dragon("Jabosh"));
monsters.add(new Troll("Salomon"));
monsters.add(new Troll("Bender"));
int damageDone = 0;
while (damageDone < 100) {
for (Monster m : monsters) {
m.move((int)(Math.random()*4) + 1);
damageDone += m.attack();
}
}
}
}
java程序
代码1:Monster.java
//import java.lang.runtime.SwitchBootstraps;
public class Monster {
public String name;
public Monster(String name) {
this.name = name;
}
public int attack() {
int x = (int) (Math.random() * 5 + 1);
System.out.println(this.name + ", of type "
+ getClass() + ", attacks generically: "
+ x + " points damage caused. ");
return x;
}
public void move(int direction) {
switch(direction) {
case 1: {
System.out.println(this.name +" is moving 1 step North. ");
break;
}
case 2:{
System.out.println(this.name +" is moving 1 step East. ");
break;
}
case 3:{
System.out.println(this.name +" is moving 1 step South. ");
break;
}
default:
System.out.println(this.name +" is moving 1 step West. ");
break;
}
}
}
代码2:Dragon.java
public class Dragon extends Monster{
public Dragon(String name){
super(name);
this.name = name;
}
@Override
public int attack() {
int probability = (int)(Math.random()*10 + 1);
int x;
if(probability <= 3) {
x = (int) (Math.random()*50 + 1);
System.out.println(this.name + ", of type "+ getClass()
+ ", attacks bby breathing fire: " + x
+ " points damage caused. ");
}
else {
x = super.attack();
}
return x;
}
}
代码3:Troll.java
public class Troll extends Monster{
public Troll(String name){
super(name);
if(name.equals("Saul") || name.equals("Salomon")){
System.out.println("This name is not available." );
this.name = "Detritus";
}
}
public String name(){
return this.name;
}
}
代码4:TestingMonster.java
import java.util.*;
public class TestingMonster {
public static void main(String[] args){
ArrayList monsters = new ArrayList();
monsters.add(new Monster("Tom"));
monsters.add(new Monster("George"));
monsters.add(new Dragon("Smaug"));
monsters.add(new Dragon("Jabosh"));
monsters.add(new Troll("Salomon"));
monsters.add(new Troll("Bender"));
int damageDone = 0;
while (damageDone < 100) {
for (Monster m : monsters) {
m.move((int)(Math.random()*4) + 1);
damageDone += m.attack();
}
}
}
}



