Karem
Karem

Reputation: 18103

Java: store to memory + numbers

Im having a function:

private void fixTurn(int turn)

And then I have:

  memory1 = memory1 + count;

Now, I would like to make, if turn is 2 it should:

  memory2 = memory2 + count;

I tried this:

  memory + turn = memory+turn + count;

But will it will not work, should i just go with an if statement?

Upvotes: 0

Views: 265

Answers (7)

Jason Rogers
Jason Rogers

Reputation: 19344

you should rephrase your quesiton but I think you want to do something like this

private void fixTurn(int turn){

    if(turn == 1){//note can be replaced by a switch
       memory1 +=count;
    }else if(turn ==2){
       memory2 +=count;
    }

Edit: the solution proposed by John Skeet is better in terms of readability and adaptability and I would recommend it more

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114797

My polished crystal ball tells me, that you that you have some sort of game, that is organized in "turns" and you want to change something for a given turn ("fixTurn").

You may want to store the turns in a list. That's preferrable over an array, because a list can grow (or shrink) and allows adding more and more "turns".

Assuming, you have some class that models a turn and it's named Turn, declare the list like:

List<Turn> turns = new ArrayList<Turn>();

Then you can add turns to it:

turns.add(new Turn());

And now, if you have to change some parameter for a turn, do it like this:

private void fixTurn(int number) {
   Turn memory = turns.get(number);
   memory.setCount(memory.getCount()+count);
}

Upvotes: 0

123
123

Reputation:

u have to write it as memory += turn * count

Upvotes: 1

Abhinav Sarkar
Abhinav Sarkar

Reputation: 23802

I am not very clear about your question but I think this is what you are looking for:

memory += turn * count

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346347

Numerical indexes in variable names are generally something to be avoided.

Wanting to access such variables via the index is usually the sign of a novice programmer who hasn't gotten the point of arrays - because an array is exactly that, a bunch of variables that can be accessed via an index:

memory[turn] = memory[turn] + count;

or, shorter (using a compound assignment operator):

memory[turn] += count;

Upvotes: 5

Enrique
Enrique

Reputation: 10127

This syntax is not allowed in java

memory + turn = memory+turn + count;

Upvotes: -2

Jon Skeet
Jon Skeet

Reputation: 1501586

No, you should use a collection of some form instead of having several separate variables. For example, you could use an array:

memory[turn] += count;

Upvotes: 7

Related Questions