0

I am trying to add a default constructor to my data type. Right below the default constructor is the problem,"ingredients = " " ; ". It gives me an error saying String cannot be converted to String[]. What do I put after the equals sign to make it compile?

import java.util.Arrays;
class Recipes {
  private String[] ingredients = new String[20];
  private String[] instructions = new String[20];

 public Recipes(){
  ingredients = "" ;
  instructions = "" ;
}

public String[] getIngredients() {
  return ingredients;
}

public void setIngredients(String[] inIngredients) {
   ingredients = inIngredients;
}

public String[] getInstructions() {
  return instructions;
}

 public void setInstructions(String[] inInstructions) {
  instructions = inInstructions;
}

  public void displayAll() {
  System.out.println("The ingredients are " + ingredients);
  System.out.println("The instructions are " + instructions);   
 }      
}

2 Answers 2

2

It doesn't make sense to assign a String ("") to String[] (an array of Strings).

You may want to do one of the following in your default constructor, depending on your requirements:

  • Do nothing. The arrays were already initialized when they were declared, even if they are full of null elements.
  • Assign the empty string "" to every element. You can use a for loop for that, or an array initializer.
  • Assign null to the arrays. You are presumably replacing the array references later by calling setIngredients and setInstructions.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the response. My instructor said he wants us to initialize both arrays so that each index in each array contains empty strings. I'm fairly new and do not know if assigning them null would fulfill his requirement.
Then you need the second option, not the first or third options.
Arrays.fill would also work, instead of the for loop.
1

You are initializing a String array reference to a single string value thats why the compiler is going nuts.

You can do this

class Recipes {
  private String[] ingredients = null;
  private String[] instructions = null;

 public Recipes(){
  ingredients = new String[5]{"","","","",""};
  instructions = new String[5]{"","","","",""};
}

I've reduced the size of the array for brevity. You can also use a for loop to assign fill in empty strings in the array if the array size is too large.

class Recipes {
      private String[] ingredients = new String[20];
      private String[] instructions = new String[20];

     public Recipes(){
      for(int i=0;i<ingredients.length;i++)
      {
      ingredients[i]="";
      instructions[i]="";
      }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.