Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects lost in array

Tags:

java

arrays

I am making a RPG-style program, but I have trouble to get my array of treasure objects to work. I want to save all treasures I find in the array, to be printed out later. Here is the code for the treasure class:

private static int x = 0;
Treasure treasureArray[] = new Treasure[20];

public void collectedTreasures(Treasure t){
treasureArray[x] = t;
x++;
}

And in the main program:

GoldTreasure t = new Coin();
hero1.setPoints(t.getCoin());
t.collectedTreasures(t);

The creation of the treasure object is within a switch within a infinite loop. When i print out the array, with method

public void printTreasures(){
        for (int y=0 ; y<x ; y++){
            System.out.print(treasureArray[y] + ", ");

I only get "null" for as many treasures there should be in the array. If i print out the array after t.collectedTreasures(t), I see that only the last treasure is there, and the indexes before that object is null. What have I done wrong?

Yes I'm a newbie. Be nice.

like image 709
SKR Avatar asked Apr 01 '26 06:04

SKR


1 Answers

This code is quite suspicious:

GoldTreasure t = new Coin();
hero1.setPoints(t.getCoin());
t.collectedTreasures(t);

It means you are:

  1. creating a new treasure t;
  2. calling collectedTreasures on that very instance.

You should assign the treasure array to the hero, not to the treasure itself.

Also note that x should not be a static variable because it will get shared among all instances; clearly not your intention, since the treasure array is per-instance.

like image 115
Marko Topolnik Avatar answered Apr 02 '26 18:04

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!