[英]If @before executes after constructor, how do you initialize the class?
[英]How do you initialize a default constructor for String Arrays?
我试图将默认构造函数添加到我的数据类型。 在默认构造函数的正下方是问题“ ingredients =“”;“。 它给我一个错误,提示无法将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);
}
}
它没有意义分配一个String
( ""
),以String[]
阵列Strings
)。
您可能需要根据自己的要求在默认构造函数中执行以下操作之一:
null
元素。 ""
分配给每个元素。 您可以for
使用for
循环或数组初始化程序。 null
分配给数组。 您大概稍后将通过调用setIngredients
和setInstructions
替换数组引用。 您正在初始化对单个字符串值的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]="";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.