0

I have to create this little method inside a class that adds a planet to a galaxy, but it seems that the element k+1 in array planeta is not replaced... is it because it's inside the if statement?

public void addPlanet(String planetName, BigInt x, BigInt y, BigInt z) {        
    if (planetExists(planetName) && !complete()){       
        newSP= new SpacePoint(x,y,z);
        newPlanet= new Planet("planetName",newSP);          
        int k=this.size();      
        planeta[k+1]=planetName; //doesnt replace because its inside the if??
    }
}

I'm sorry if it's an easy question, I'm taking java classes in college and I'm really new... PS: btw thank you all, you've been my teachers for these days!! =)

2
  • What do the methods planetExists and complete do? Commented Apr 9, 2013 at 20:22
  • planetExists checks if the planetName exists in array planeta, complete checks if the Galaxy is complete. The problems remains, can't replace the value and don't know why... (btw I have to use arrays because my teacher won't let us use ArrayList.....) Commented Apr 10, 2013 at 20:00

1 Answer 1

3

I suspect the problem is that you should actually be replacing planeta[k] - and incrementing size, too.

Arrays are 0-based in Java, so if your size is 2, your array might have values:

planeta[0] = "Earth";
planeta[1] = "Jupiter";

... so the next slot to fill would be planeta[2], and increment the size to 3.

A better alternative would be to use a List<String> (e.g. an ArrayList<String>) so you could just call add, and you wouldn't need to worry about overflowing the bounds of the array, etc.

Sign up to request clarification or add additional context in comments.

4 Comments

I've initialized the array planeta with 5000 elements (the capacity of the galaxy) with "NA". Doesn't seem to solve, but I think I will try ArrayList<String> (my teacher hasn't talked about it yet, but it's worth the shot!) thank you!
@JoanaSalvado: You should work out what's wrong with the current code before changing it. What makes you think that the change to the array doesn't work?
After I call addPlanet(...) I check if there is a planet named "planetnName" and java says that doesn't...
I've changed the code based in ArrayList<String> and it's the same...doesn't add the element, it only adds if it's outside the if!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.