I'm trying to compile a code that's using composition. My goal is to implement data validation code to make sure that when an object is instantiated, the scores that I'm using are greater than zero and less than 300. I've been attempting to throw an IllegalArgumentException, but whenever I compile the whole thing with a negative integer or an integer greater than 300, I don't receive any error message for the value and the code continues to run as normal. I just wanna know if anyone can lead me towards the right direction and give me some suggestions. Here's the code I came up with:
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);
}
}
Here's my code that compiles the username:
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);
}
}
And finally the test code:
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);
}
}