我最近刚开始学习java,我遇到了一个关于setter验证的问题,下面是字符串类型的setter验证,我应该写什么来做boolean和double的setter校验?下面是我为string编写的代码。
public class Person
{
private String name;
private String id;
private boolean isNew;
private double bonus
public Person()
{
this("Unknown","unknown",true,0.0);
}
public Person(String id,String name,boolean isNew,double bonus)
{
setId(id);
setName(name);
setIsNew(isNew);
setBonus(bonus);
}
public getId()
{
return id;
}
public getName()
{
return name;
}
public setId()
{
this.id = id;
}
public setName()
{
this.name = name;
}
public void display()
{
System.out.println("Id:" + id);
System.out.printoutln("Name:" + name);
}
// setter validation for string
public void setName(String name)
{
if(name == null)
{
throw new IllegalArgumentException("A valid name must be provided ");
}
name = name.trim();
if(name.length() ==0)
{
throw new IllegalArgumentException("Name must not be blank ");
}
this.name = name;
}
// setter validation for id
public void setId(String id)
{
if(id == null)
{
throw new IllegalArgumentException("A valid id must be provided ");
}
id = id.trim();
if(id.length() ==0)
{
throw new IllegalArgumentException("Id must not be blank ");
}
this.id = id;
}
}
我最近刚开始学习java,我遇到了一个关于setter验证的问题,下面是字符串类型的setter验证,我应该写什么来做boolean和double的setter校验?
-
当您想要返回值时,您必须声明返回类型,例如"public字符串getId(("取而代之的是";public getId((";。
-
Setter需要一个参数。示例:";public setId(字符串id(";。
-
所有args构造函数应该看起来像:
public Person(String name, String id, boolean isNew, double bonus) {this.name = name; this.id = id;this.isNew = is;this.bonus = bonus; }
-
对于布尔参数构造函数,需要值。如果您想验证某个内容,可以将类型更改为Boolean并处理NullPointerExeption。或者创建自定义异常:
公共类MyWrongBooleanException扩展了RuntimeException{public IncorrectFileExtensionException(字符串错误消息,可抛出错误({super(errorMessage,err(;}}