JAVA Lab 5 答案与解析 problem1

package problem1;

public class Monster
{
	String name;

	public Monster(String name)
	{
		this.name = name;
	}

	public int attack()
	{
		int x;

		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;
		}
	}

}
备注:生成随机数1-x:  math.random()*x+1
package problem1;

public class Dragon extends Monster
{
	public Dragon(String name)
	{
		super(name);
		this.name = name;
	}

	// override the attack
	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 by breathing fire: " + x
					+ " points damage caused.");

		} else
		{
			x = super.attack();
		}
		return x;

	}
}

Note:
难点1:30% of the time
解决思路: 生成一个1-10 的随机数 然后 若1-3 则使用breathing the fire 来攻击
难点2: 如何一起使用 breathing the fire 与 常规攻击?

x = super.attack();
package problem1;

public class Troll extends Monster
{

	public Troll(String name)
	{

		super(name);
//		this.name = name;
		if (name.equals("Saul") || name == "Salomon")
		{
			System.out.println("wrong name");
			this.name = "Detritus";

		}
	}

	public String getName()
	{
		return this.name;
	}

}

Note:
1、对于super的理解:使用父类的此方法,里面的东西就不用再写了,super括号里面就是给父类对应方法传的参数
2、对于equals的理解: equals() 是一个class中的一种方法,可以比较此 . 前面对应的值 和括号里面的值是否相等

 public boolean equals(Object obj) {
        return (this == obj);
    }

如比较两个字符串是否相等:
String s1 = “fang”;
boolean test = s1.equals(“fang”)// true
(别忘了要有一个 boolean值 承接equals 返回的值)

package problem1;

import java.util.ArrayList;

public class TestingMonster
{
	public static void main(String[] args)
	{
		ArrayList<Monster> monsters = new ArrayList<>();
		monsters.add(new Monster("Tom"));
		monsters.add(new Monster("Geooge"));

		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 = damageDone + m.attack();
			}
		}

	}

}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值