在一款角色扮演游戏中,每一个人都会有名字和生命值,角色的生命值不能为负数。
要求:当一个人物的生命值为负数的时候需要抛出自定义的异常
操作步骤描述:
(1)自定义异常类NoLifeValueException继承RuntimeException
(2)定义Person类
①属性:名称(name)和生命值(lifeValue)
②提供空参构造
③提供有参构造:使用setXxx方法给name和lifeValue赋值
④提供setter和getter方法:
在setLifeValue(int lifeValue)方法中,首先判断,如果 lifeValue为负数,就抛出NoLifeValueException,异常信息为:生命值不能为负数;
然后在给成员lifeValue赋值。
⑤重写toString方法
回答:真的是C++代码吗,真想用Java来写
package com.boot.tank;
/**
* @author bbyh
* @date 2022/11/4 0004 10:01
* @description
*/
public class Person {
private String name;
private Integer lifeValue;
public Person() {
}
public Person(String name, Integer lifeValue) {
setName(name);
setLifeValue(lifeValue);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLifeValue() {
return lifeValue;
}
public void setLifeValue(Integer lifeValue) {
if (lifeValue < 0){
throw new NoLifeValueException("生命值不能为负数");
}
this.lifeValue = lifeValue;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", lifeValue=" + lifeValue +
'}';
}
/**
* @author bbyh
* @date 2022/11/4 0004 10:02
* @description
*/
static class NoLifeValueException extends RuntimeException {
public NoLifeValueException(String message) {
super(message);
}
}
public static void main(String[] args) {
Person jack = new Person("Jack", 30);
System.out.println(jack);
Person mary = new Person("Mary", -30);
System.out.println(mary);
}
}
C++版本的写不来呀