Reputation: 18103
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
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
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
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
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
Reputation: 10127
This syntax is not allowed in java
memory + turn = memory+turn + count;
Upvotes: -2
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