包含对象数组的对象

时间:2013-12-22 12:35:10

标签: java arrays class object nullpointerexception

我可以将对象(成分)分配给主类中的数组,如下所示:

  

Ingredient[] ingredient = new Ingredient[5];
  Ingredient potato = new Ingredient("Potatoes");
  ingredient[0] = potato;

但我真正想做的是将数组放在另一个对象(食物)中,所以我可以像这样访问它:

  

fries.ingredient[0] = potato;

这样每种食物都有自己的成分。但是,我尝试过的所有内容都会导致'NullPointerException'或'找不到符号'。我该如何解决这个问题?

修改
抱歉,需要一段时间。我不知道如何在blockquotes里面缩进,但是这里有。这是我的(失败)尝试导致NullPointerException。

Main.java:

  

public class Main {
  public static void main (String[] args) {
  Ingredient potato = new Ingredient("Potatoes");
  Food fries = new Food("Fries");
  fries.ingredient[0] = potato;
  } }

Food.java:

  

public class Food {
  Ingredient[] ingredient;
  String name;
  public Food(String name) {
  this.name = name;
  Ingredient[] ingredient = new Ingredient[5];
  } }

Ingredient.java

  

public class Ingredient {
  String name;
  public Ingredient(String name) {
  this.name = name;
  } }

4 个答案:

答案 0 :(得分:1)

在你的构造函数中,你有这个:

Ingredient[] ingredient = new Ingredient[5];

您已声明名为ingredient本地变量,它会隐藏同名的实例变量。将该行更改为

this.ingredient = new Ingredient[5];

作为学习的下一步,请考虑使用List<Ingredient>代替数组。除了其他不便之外,阵列是不可调整大小的。基本上,它们的主要用途是实现的内部,而不是客户端代码。

答案 1 :(得分:0)

您应该按以下代码执行此操作:

Ingredient potato = new Ingredient("Potatoes");
fries = new ClassName(); //Replace with your class Constructor method
fries.ingredient = new Ingredient[5];
fries.ingredient[0] = potato;

修改

你的食物课必须是这样的:

public class Food {
    Ingredient[] ingredient;
    String name;

    public Food(String name) {
        this.name = name;
        this.ingredient = new Ingredient[5];
    }
}

和主要课程:

public class Main {
    public static void main(String[] args) {
        Ingredient potato = new Ingredient("Potatoes");
        Food fries = new Food("Fries");
        fries.ingredient[0] = potato;
    }
}

和成分类

public class Ingredient {
    String name;

    public Ingredient(String name) {
        this.name = name;
    }
}

答案 2 :(得分:0)

创建一个类:

public class Food{
   public Object[] ingredient;
   public food(int numOfIng){
        this.ingredients=new Object[numOfIng]
   }
}

现在就做:

Food fries=new Food(5);
Ingredient potato = new Ingredient("Potatoes");
fries.ingredient[0] = potato;

答案 3 :(得分:0)

你可以尝试通过界面来做,所以我想像:

interface Food {

   void takeInfo();
}

public class FoodSelection{

private List<Food> listOfFood = new ArrayList<>();

public void selectFries(){
  initFood(new Fries());
}

// other food...

public void initFood(Food food){
food.takeInfo();
listOfFood.add(food);
}

}

现在是时候创建薯条类..

class Fries implements Food{

private String[] ingredients;

public void takeInfo(){
   // declare Fries ingredients.
}

}

所以,打电话给它做这样的事情:

FoodSelection takeFood = new FoodSelection();

takeFood.selectFries();