This site requires JavaScript, please enable it in your browser!
Greenfoot back
SallySanban
SallySanban wrote ...

2017/2/20

How do you access variables from a different method in the same class?

SallySanban SallySanban

2017/2/20

#
I am a beginner in Greenfoot and I am making a mystery, thriller game with backstories and user interaction. I am trying to use string concatenation so that I can ask for the user's name using Greenfoot.ask() and show the text using GreenfootImage, like so:
String name = Greenfoot.ask("Allyson:" + newline + "What's your name?");
setImage(new GreenfootImage("You:" + newline + "Hey. I'm " + name + ". Nice to meet you.", 22, Color.BLACK, Color.WHITE));
I could do that in the same method I initiated the variable 'name', but since I have a lot of backstories, I have many many methods, with one method per backstory. I cannot seem to access the variable 'name' in a different backstory, which means I can only mention the player's name once throughout the entire game, unless I ask for it again which is inconvenient.
davmac davmac

2017/2/20

#
You should probably declare the variable as an instance variable rather than a local variable. To do that, declare it outside of all methods (but still inside the class body):
String name;
You can still assign and use it within the method body:
name = Greenfoot.ask("Allyson:" + newline + "What's your name?");
Make sure you remove the type ("String") from the assignment in the method body; otherwise, you are still declaring a (second) variable.
SallySanban SallySanban

2017/2/20

#
Thank you so much! It really works. :)
You need to login to post a reply.