Reputation: 57
Im making a battleship game I have 3 classes and a driver.
in the player class
i have this method
public void hitownshiporGrenade(String[][] grid, String attack) {
// checking if attack hits our ship, appropriate
// if it does place an s in the array
if (attack.equals(s1)) {
// -97 gives us a starting point at 0 for 'a' to
// store in array, same for 49 and '1'
grid[attack.charAt(0) - 97][attack.charAt(1) - 49] = "s ";
System.out.println("ship hit!");
s1Sunk = true;
}
I have the declared variable and a getter on top
private boolean s1Sunk;
public boolean isS1Sunk() {
return s1Sunk;
}
Now in my other class
Player player = new Player();
System.out.println(player.isS1Sunk());
if i call this in a method in the driver it stays false nomatter what even if the first methods condition makes it true;
Upvotes: 0
Views: 192
Reputation: 2500
Assuming the methods you mentioned in your code sample all belong to the same Player
class definition, then creating a new class instance (an object) of Player
by doing
Player player = new Player();
you create a new, separate (from all others) instance of the Player
class. Unless you run hitownshiporGrenade
for that SPECIFIC object, its variables aren't going to change.
Consider the following:
Player player1 = new Player(); //player1.isSunk is false
Player player2 = new Player(); //player2.isS1Sunk is again false,
//and separate from player1.isS1Sunk
player1.hitownshiporGrenade(foo, bar) //This changes player1.isSunk to true
System.out.print(player1.getIsSunk()); //true, assuming lucky hits
System.out.print(player2.getIsSunk()); //false
I'd also recommend you read up on using proper Camel case when naming your variables! It's going to make your code much easier to read, and save you a lot of headache when you're going through it.
Upvotes: 1