Home How do you pass an updated global class variable from one method into another?
Reply: 1

How do you pass an updated global class variable from one method into another?

brodingoson
1#
brodingoson Published in 2017-12-05 01:16:44Z

I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method. Any help would be appreciated, thank you. Here's my shortened code:

public class Game{

    private int randomIndexX;

    protected String spawn(){
        randomIndexX = randomGenerator.nextInt(10);
        return null;
    }

    protected String test(){
        System.out.println(this.randomIndexX);
        return null;
    }
}


public class Player extends Game{
    protected String getNextAction(String command) {
        switch(command){
            case "test":
                test();
                break;
        }
    }
}


public static void main(String[] args) {
    Game game = new Game();
    Player player = new Player();

    game.spawn();
    player.getInputFromConsole();
}

EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()

Sapphire
2#
Sapphire Reply to 2017-12-05 01:45:53Z

The first problem I can see is that you don't have a constructor.(Optional) (If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.

The second problem I can see is that you missing the end bracket. Fix shown below.

public class Game

{

private int randomIndexX;

protected String spawn()
{
    randomIndexX = 0;
    return null;
}

protected String test()
{
    System.out.println(randomIndexX);
    return null;
}

}

You can construct it and trigger any methods you wish:

Game game = new Game();
game.spawn();
game.test()
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30881 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO