每次循环运行不同的方法

时间:2014-10-10 02:57:13

标签: java loops switch-statement case

我的目标是通过循环

运行此代码来减少代码
each_score = ones(dice_values);
total_score += each_score;
end_scores += String.valueOf(each_score) + " ";

接着是

each_score = twos(dice_values);
total_score += each_score;
end_scores += String.valueOf(each_score) + " ";

唯一的区别是第一行的方法。我不知道通过类似for循环的方式做这样的事情的方法,宁愿不复制粘贴代码13次。 (如果可能的话,我也希望能有比切换机更高效的东西)

private static int ones(int[] dice_values) {
    int ones = 0;
    for(int i = 0; i < 5; i++)
        if(dice_values[i] == 1)
            ones++;     
    return ones;
}

private static int fours(int[] dice_values) {
    int fours = 0;
    for(int i = 0; i < 5; i++)
        if(dice_values[i] == 4)
            fours++;        
    return (fours * 4);
}


private static int five_of_kind(int[] dice_values) {
    int five_kind = 0;
    int[] five_of = new int[5];
    for(int i = 0; i < 5; i++)
        five_of[dice_values[i] - 1]++;

    if(Arrays.asList(five_of).contains(5))
        five_kind = 50;
    return five_kind;
}

这是方法的一个示例。我正在解决一个叫做Yahtzee的简单问题。给定一组13个5个骰子的卷,找到所有卷的总得分和每个得分点的总数(这些点是“一个:多少个”或“五个”作为例子)。 / p>

3 个答案:

答案 0 :(得分:1)

除非我遗漏了某些内容(并且没有switch),否则您可以构建一个int分数数组并迭代该scores数组。这就像

int [] scores = new int[] {
        ones(dice_values), twos(dice_values), threes(dice_values), 
        fours(dice_values), fives(dice_values), sixes(dice_values), 
        sevens(dice_values), eights(dice_values), nines(dice_values),
        tens(dice_values), elevens(dice_values), twelves(dice_values),
        thirteens(dice_values)
};
for (int each_score : scores) {
    total_score += each_score;
    end_scores += String.valueOf(each_score) + " ";
}

答案 1 :(得分:1)

您可以在此方案中使用反射,

string[] methodNames = new string{}["ones","twos",....];
for(string method : methodNames)
{
    Method method = this.getClass().getMethod(dice_values.getClass());
    each_score = method.Invoke(this,dice_values);
    total_score += each_score;
    end_scores += String.valueOf(each_score) + " ";
}

答案 2 :(得分:0)

for(int i = 1; i <= 13; i++) {
    switch(i) {
        case 1:
            each_score = ones(dice_values);
        break;

        case 2:
            each_score = twos(dice_values);
        break;

        ...

    }
    total_score += each_score;
    end_scores += String.valueOf(each_score) + " ";
}