2015-05-05 35 views
0

我想添加一个默认构造函数到我的数据类型。在默认构造函数下面是问题,“ingredients =”“;”。它给我一个错误说,字符串不能转换为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); 
}  
} 

回答

1

您正在初始化一个字符串数组引用单个字符串值,这就是为什么编译器疯了。

你可以做到这一点

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]=""; 
     } 
    } 
2

它没有意义分配一个String"")至String[](的Strings阵列)。

你可能想要做你的默认构造函数根据您的要求下,之一:

  • 什么也不做。阵列在声明时已经初始化,即使它们充满了null元素。
  • 将空字符串""分配给每个元素。您可以使用for循环或数组初始值设定项。
  • null赋值给数组。您大概可以通过调用setIngredientssetInstructions来替换数组引用。
+0

谢谢你的回应。我的老师说他希望我们初始化两个数组,以便每个数组中的每个索引都包含空字符串。我是相当新的,不知道将它们分配给null是否会满足他的要求。 – James

+0

然后,您需要第二个选项,而不是第一个或第三个选项。 – rgettman

+2

'Arrays.fill'也可以,而不是for循环。 –

相关问题