【问题标题】:Java: 2D array into 1D array with organisation and random numbersJava:将二维数组转换为具有组织和随机数的一维数组
【发布时间】:2015-10-24 16:22:23
【问题描述】:

我想总结每位参赛者从每位评委那里获得的分数(存储在二维数组中),我希望将其汇总为一维数组。例如:

参赛者一:

评委1:5分

裁判2:3分

方法应该这样做:array[0] = 5+3

这是我创建的,但是如果judge 大于contestant,它就不起作用,我也不相信它可以正常工作。我试过调试没有任何进一步的成功。 allPoints 是包含所有信息的二维数组;例如,allPoints[0][0]judge 1contestant 1 的。

有什么想法吗?

int output = 0;
        for (int t = 0; t < judge; t++) {
            for(int i = 0; i < contestant; i++) {
                output += allPoints[t][i];
            }
            Sum[t] = output;
            output = 0;
        }

【问题讨论】:

  • 您能否分享一下您是如何创建变量的详细信息,allPointsSum 最受关注。
  • 你可能需要 Sum[t] 成为 Sum[i]。我相信每个参赛者都有一笔与他相关的金额,而不是每个评委。
  • 你的循环可能也搞混了。
  • 显示初始化allPoints的代码。使用您显示的代码,每一行都是评委,每个参赛者是一列

标签: java arrays 2d


【解决方案1】:

可能你在循环中混淆了。 如果我完全猜到您的问题,那么解决方案将是

    int output = 0;
    for(int i=0; i<contestant; i++){
        for(int t=0; t<judge; t++){
            output+= allPoints[t][i];  //It has a chance to be  allPoints[i][t] according how  you generate allPoints
        }
        Sum[i] = output;
        output = 0;
    }

对于每个contestant 计算所有judge 给出的总分并将其放入Sum。所以Sum 持有每个contestant 的总分。

【讨论】:

  • 谢谢!!我差点把我的电脑从窗户扔出去!
【解决方案2】:

如果 allPoints[i][j],如果 i 是裁判,j 是参赛者。您需要验证这一点。正确的代码是:

int output = 0;
for (int j = 0; j < contestant; j++) {
    for(int i = 0; i < judge; i++) {
        output += allPoints[i][j];
    }
    Sum[j] = output;
    output = 0;
}

基本上,对于每个参赛者,您需要对每个评委给出的分数求和。您现在所做的就是为每位评委总结他给所有参赛者的分数。

【讨论】:

    猜你喜欢
    • 2016-10-30
    • 1970-01-01
    • 2016-02-18
    • 2018-02-19
    • 2021-11-23
    • 2021-07-20
    相关资源
    最近更新 更多