开发者

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:

  mem开发者_StackOverflow中文版ory2 = memory2 + count;

I tried this:

  memory + turn = memory+turn + count;

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


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;


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;


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


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


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);
}


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

memory += turn * count


This syntax is not allowed in java

memory + turn = memory+turn + count;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜