0

Basically, I want to throw a new TruckException if the String array parameter materials is null when we create a new Truck via its constructor. What should I do in the if statement to verify if the String array materials is null?

{
  private String[] materials = new String[5];

  private long permit = 0;

  private String company = "";


  public Truck(String[] materials, long permit, String company, String ownerName, String ownerAddress, String brand, String model, String licencePlate, float value) throws TruckException, VehicleException
  {
    super(ownerName, ownerAddress, brand, model, licencePlate, value);

    setMaterials(materials); //on ne fait pas setMaterial(this.materials) car setMaterials modifie this.materials 
    if(materials.length == 0 || materials.length>5 // ||???) //this if statement
      throw new TruckException("materials");
    
    this.company = company;
    if(company.equals(""))
      throw new VehicleException("company");

//rest of code...


}```
6
  • If the array itself is null? Or if contains null elements? Commented Nov 26, 2023 at 3:47
  • It says "the exception must be thrown by the constructor of the Truck class if the array received for materials is empty or null or if it contains more than five elements." Commented Nov 26, 2023 at 3:51
  • 1
    So just check if materials == null. Not sure what the question is. Commented Nov 26, 2023 at 3:52
  • It's what I tried initially but my code returns java.lang.NullPointerException instead of dt.TruckException when I test it Commented Nov 26, 2023 at 3:54
  • 2
    if (materials == null || materials.length == 0) { throw new TruckException(); } <-- Obviously this check must be done before you try to use the array. Commented Nov 26, 2023 at 3:55

1 Answer 1

0

if (materials == null || materials.length == 0) { throw new TruckException(); }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.