Helpp Helpp - 1 year ago 65
Java Question

How to access an array within an object?

I am relatively new to Java, and also object oriented programming. I am trying to create an object inside an array within another object, however, I am getting errors in compiling, showing error: cannot find symbol.

So basically I have an object called PokeBoxes, and another object Pokemon. I have to deposit the Pokemon into the PokeBoxes, and once the PokeBox is full, it will automatically deposit in the next box available.

These are my constructors for both Objects

class PokeBox {

public PokeBox(int boxCapacity) {
_boxCapacity = boxCapacity;
Pokemon[] storage = new Pokemon[_boxCapacity];
}

public void putInBox(int i, int boxIndex, String pokemonName, int level) {
this.storage[index] = new Pokemon(pokemonName, level, "box" + String.valueOf(boxIndex));


and

class Pokemon {
String pokemonName, _location;
int pokemonLevel;

public Pokemon(String name, int level, String location) {
pokemonName = name;
pokemonLevel = level;
_location = location;
}
public String getName() {
return this.pokemonName;
}

public int getLevel() {
return this.pokemonLevel;
}

public String getLocation() {
return this._location;


The problem I'm facing now is this line:

public void putInBox(int index, int boxIndex, String pokemonName, int value) {
this.storage[index] = new Pokemon(pokemonName, level, "box" + String.valueOf(boxIndex+1));


I'm assuming I cannot use
this.storage[index]
, so what can I do to solve it?

Answer Source

Declaring the array storage as a class member will resolve the scope issue you have:

class PokeBox {
 private Pokemon[] storage;
 public PokeBox(int boxCapacity) {
      _boxCapacity = boxCapacity;
      storage = new Pokemon[_boxCapacity];
  }

that way you have the guaranty that your array is visible to any method inside that class

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download