Tristan
Tristan

Reputation: 23

How can I define a variable within an object with another variable

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

Answers (3)

That doesn't work since Java is a Statically-Typed Language unlike JavaScript or Lua.

So,

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

lkq
lkq

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

Suresh Atta
Suresh Atta

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

Related Questions