如何初始化String Arrays的默认构造函数?

时间:2015-05-05 21:54:13

标签: java arrays

我正在尝试向我的数据类型添加默认构造函数。在默认构造函数的正下方是问题," ingredients =" " ; &#34 ;.它给出了一个错误,说String不能转换为String []。我在等号后面放什么来编译?

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 个答案:

答案 0 :(得分:2)

String"")分配给String[]Strings数组)是没有意义的。

您可能希望在默认构造函数中执行以下操作之一,具体取决于您的要求:

  • 什么都不做。这些数组在声明时已经初始化,即使它们充满了null元素。
  • 将空字符串""分配给每个元素。您可以使用for循环或数组初始化程序。
  • null分配给数组。您可能稍后通过调用setIngredientssetInstructions来替换数组引用。

答案 1 :(得分:1)

您正在将String数组引用初始化为单个字符串值,这就是编译器疯狂的原因。

你可以这样做

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

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

为简洁起见,我减小了阵列的大小。如果数组大小太大,您还可以使用for循环在数组中指定填充空字符串。

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]="";
      }
    }
相关问题