开发者

Proper way to handle "check list" of items

开发者 https://www.devze.com 2023-03-13 20:09 出处:网络
I have a process that must complete a set of tasks. It is possible that the process will try attempt a task that has already been completed, in which case it should ignore the attempt and generate a r

I have a process that must complete a set of tasks. It is possible that the process will try attempt a task that has already been completed, in which case it should ignore the attempt and generate a request to complete another task. I am not sure of a good way to track which tasks are completed and which still need to be processed.

I will use the game "Yahtzee" as an example to demonstrate how I am currently handling this. I first create the list of tasks, in this case the scoring combinations:

com开发者_StackOverflowbinations = new ArrayList<String>();
combinations.add("one");
combinations.add("two");
...
combinations.add("fullhouse");
combinations.add("smallstraight");
combinations.add("yahtzee");
...

When the player uses one of these combinations, I remove it from the arraylist, in this case the "small straight" combination:

public void selectSmallStraight() {
    int index = combinations.indexOf("smallstraight");
    if(index < 0)
        System.out.println("Small Straight already used");
        //Prompt the player for another selection
    else
        combinations.remove(index);
        score += 30;
}

Once all of the combinations have been used, the game ends.

Using an array list seems very primitive to me, not to mention ugly. I have considered using a Map<String, Boolean> and then just marking the object as false once it has been used, but I would assume there is already some "standard" way of doing this much more elegant.


If a primitive solution works, then that's often the best solution. Why make it more complicated?

The only disadvantage I can see with using just an ArrayList is that searching in it is slow. Using a Map for this would be better.

But it may be even better if you created a class that knows whether it was already used and put that into a map.


Your arraylist example may be a bit inefficient for what you're doing, and it has the possibility of accidentally mistyping an action. If you have a set number of actions, why not keep them in a boolean array?

final static int FIRSTACTION = 0;
final static int SECONDACTION = 1;
final static int LASTACTION = 2;
boolean[] actionsFinished = new boolean[3];

Then you can set it after finishing:

//Do first action code goes here
actionsFinished[FIRSTACTION] = true;
0

精彩评论

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