0

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"

2
  • 1
    "so that it will define it within the object" - Can you elaborate, or at least use fewer pronouns? Commented Apr 21, 2016 at 18:36
  • @Zircon mainsave. b = a should come out to something like mainsave.axe = 1 Commented Apr 21, 2016 at 18:38

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So would I have to create a method for each individual item that I want to pass on?
@Tristan Yes. Overloading.
0

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

4 Comments

-1, because for as trivial things as storing some data in a SaveFile class nobody should be using Reflection. (nobody should use it for non-trivial things either, for that matter)
OP could also use ASM to edit the bytecode at runtime to implement non-statically typed languages features in Java. But just because you can do it, doesn't mean you should.
Don't be silly. Nobody should do something as stupid as that
sorry, kinda in a bad mood at the moment
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.