我正在尝试编译使用合成的代码。我的目标是实现数据验证代码,以确保在实例化对象时,我使用的分数大于零且小于300.我一直在尝试抛出IllegalArgumentException,但每当我编译整个带有负整数或大于300的整数的东西,我没有收到任何值的错误消息,代码继续正常运行。我只想知道是否有人能引导我朝着正确的方向前进并给我一些建议。这是我提出的代码:
public class ScoresClass
{
private int score0;
private int score1;
private int score2;
private int score3;
public ScoresClass(int a, int b, int c, int d)
{
if (score0 < 0 || score0 >= 300)
throw new IllegalArgumentException("Score must be between 0 - 300");
if (score1 < 0 || score1 >= 300)
throw new IllegalArgumentException("Score must be between 0 - 300");
if (score2 < 0 || score2 >= 300)
throw new IllegalArgumentException("Score must be between 0 - 300");
if (score3 < 0 || score3 >= 300)
throw new IllegalArgumentException("Score must be between 0 - 300");
this.score0 = a;
this.score1 = b;
this.score2 = c;
this.score3 = d;
}
public String toString()
{
return String.format("Score 0: %d%n Score 1: %d%n Score 2: %d%n "
+ "Score 3: %d%n", score0, score1, score2, score3);
}
}
这是我编译用户名的代码:
public class BowlerClass
{
private String fName;
private String lName;
private ScoresClass value;
public BowlerClass(String first, String last, ScoresClass amount)
{
this.fName = first;
this.lName = last;
this.value = amount;
}
public String toString()
{
return String.format("%s %s%n %s", fName, lName, value);
}
}
最后是测试代码:
public class BowlerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ScoresClass a = new ScoresClass(5000, 150, 200, 250);
BowlerClass b = new BowlerClass("Paul", "McCartney", a);
System.out.println(b);
}
}
答案 0 :(得分:2)
您的字段score0
到score3
初始化为0.您必须在检查值是否有效之前设置它们。
或者,这里更合适的方法是检查a
,b
,c
和d
是否有效,而不是检查字段。< / p>
答案 1 :(得分:0)
使用IllegalArgumentException
是一个非常好的主意,但您应该检查参数而不是实例变量。在知道参数正常之前不要修改实例变量,否则仍然会使对象处于不正确的状态。
此外,您可以通过添加参数名称和参数值来增强消息,这将有助于找到错误原因并解决它。
public ScoresClass(int a, int b, int c, int d)
{
if (a < 0 || a >= 300)
throw new IllegalArgumentException("Score 'a' must be between 0 - 300 :" + a);
if (b < 0 || b >= 300)
throw new IllegalArgumentException("Score 'b' must be between 0 - 300: " + b);
if (c < 0 || c >= 300)
throw new IllegalArgumentException("Score 'c' must be between 0 - 300: " + c);
if (d < 0 || d >= 300)
throw new IllegalArgumentException("Score 'd' must be between 0 - 300: " + d);