我正在尝试向我的数据类型添加默认构造函数。在默认构造函数的正下方是问题," 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);
}
}
答案 0 :(得分:2)
将String
(""
)分配给String[]
(Strings
数组)是没有意义的。
您可能希望在默认构造函数中执行以下操作之一,具体取决于您的要求:
null
元素。""
分配给每个元素。您可以使用for
循环或数组初始化程序。null
分配给数组。您可能稍后通过调用setIngredients
和setInstructions
来替换数组引用。答案 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]="";
}
}