请用代码描述:
在一款角色扮演游戏中,每一个人都会有名字和生命值;角色的生命值不能为负数
要求:当一个人物的生命值为负数的时候需要抛出自定的异常
详细步骤:
1.自定义异常类NoLifeValueExption继承RuntimeException
a)提供空参和有参构造
b)在有参构造中,需要调用父类的有参构造,把异常信息传入
2.定义Person类
a)属性:名称(name)和生命值(lifeValue)
b)提供空参构造
c)提供有参构造;
i.使用setXxx方法给name和lifeValue赋值
d)提供setter和getter方法
i.在setLifeValue(int lifeValue)方法中
1.首先判断,如果 lifeValue为负数,就抛出NoLifeValueException,异常信息为:生命值不能为负数:xxx.
2.然后在给成员lifeValue赋值.
3.定义测试类Test
a)提供main方法,在main方法中
1.使用满参构造方法创建Person对象,分数传入一个负数,运行程序
2.由于一旦遇到异常,后面的代码的将不在执行,所以需要注释掉上面的代码
3.使用空参构造创建Person对象
4.调用setLifeValue(int lifeValue)方法,传入一个正数,运行程序
5.调用setLifeValue(int lifeValue)方法,传入一个负数,运行程序
求助各位大佬帮助解决.....

解决方案 »

  1.   


    package test;
    public class NoLifeValueException extends RuntimeException{
    private static final long serialVersionUID = 1L;
    private String message; public NoLifeValueException(String message) {
    super(message);
    this.message = message;
    }
    public NoLifeValueException() {
    super();
    }
    }package test;public class Person {
    private String name;
    private int lifeValue;
    public Person() {
    super();
    }
    public Person(String name, int lifeValue) {
    super();
    if(lifeValue<0){
    throw new NoLifeValueException("生命值不能是负数:"+lifeValue);
    }else{
    this.lifeValue = lifeValue;
    }
    this.name = name;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public double getLifeValue() {
    return lifeValue;
    }
    public void setLifeValue(int lifeValue) {
    this.lifeValue = lifeValue;
    }
    }package test;public class Test {
    public static void main(String[] args) {
    Person p =new Person("张三",-1);
    Person p1 =new Person();
    p1.setLifeValue(1);
    p1.setLifeValue(-1);
    }
    }