Reputation: 23
The title might be a little confusing but what I want to know is how can I change the ' b ' part in mainsave.b so that it will define it within the object.
Here is my code so far
public void getItem(int a, String b)
{
mainsave.b = a;
}
The values are being sent from this piece of code in another class called Story. I want them to be stored in the object of class SaveFile which is what 'mainsave' is
if (command_string.equals("1"))
{
try {Thread.sleep(1500);} catch (InterruptedException e) {}
System.out.println("You search the shed thouroughly and find an axe but not much else...");
int item = 1;
String axe = "axe";
getItem(item,axe);
try {Thread.sleep(1500);} catch (InterruptedException e) {}
area1();
}
The error I get when trying to compile the first part is "cannot find symbol - variable b"
Upvotes: 0
Views: 93
Reputation: 581
That doesn't work since Java is a Statically-Typed Language unlike JavaScript or Lua.
I would suggest you use some sort of List
for actually storing the data instead of a lot of fields in your SaveFile
class.
Upvotes: 0
Reputation: 2366
Usually you define getters and setters for each of you fields.
Though it's not recommended, you could achieve this by reflections.
Object a = new A();
Class<?> c = a.getClass();
Field fieldValue = c.getDeclaredField("value");
fieldValue.setInt(a, 10);
Getting and Setting Field Values
Upvotes: 0
Reputation: 121998
Simply you cannot since Java is a statically typed language. So variables names must realize at compile time.
I don't suggest but possible with reflection coding.
Upvotes: 1