简体   繁体   English

使用 ArrayList 中的内容填充二维数组

[英]Filling a 2d array with contents from an ArrayList

I have a file that is formatted as follows:我有一个格式如下的文件:

Name|Test1|Test2|Test3|Test4|Test5|Test6|Test7|Test8|Test9|Test10   
John Smith|82|89|90|78|89|96|75|88|90|96
Jane Doe|90|92|93|90|89|84|97|91|87|91
Joseph Cruz|68|74|78|81|79|86|80|81|82|87
Suzanne Nguyen|79|83|85|89|81|79|86|92|87|88
Richard Perez|100|84|73|81|92|84|95|96|95|100
Ivan Dyer|77|91|90|75|97|94|76|89|90|92
Craig Palmer|91|84|98|89|82|75|78|96|100|97
Madeline Rogers|75|79|78|93|91|76|80|88|100|81
Chelsea Roxas|87|94|89|96|95|85|88|92|86|86
Jasper Bautista|100|83|93|100|98|97|96|97|97|98

I have created an ArrayList that is populated left to right with the integers from the table above.我创建了一个 ArrayList,它用上表中的整数从左到右填充。 I confirmed that all the numbers are in the ArrayList.我确认所有数字都在 ArrayList 中。 What I am trying to accomplish is getting the average of the columns, so I thought that using a 2d array is doable, but I am having a hard time figuring out the correct for-loop syntax to properly fill the array.我想要完成的是获取列的平均值,所以我认为使用二维数组是可行的,但我很难找出正确的 for 循环语法来正确填充数组。

If anyone has any other solution apart from mine or would like to help me out, I would really appreciate it!如果有人有我以外的任何其他解决方案或想帮助我,我将不胜感激!

Edit: I have tried the following:编辑:我尝试了以下方法:

int len = tests.length;
for(int i = 0; i < len; i++){
      for(int j = 0; j < len; j++)
      {tests[i][0] = (Double) testScores.get(i);
       tests[0][j] = (Double) testScores.get(j);
      }
    }

Which yields this output:这产生了这个输出:

[[82.0, 89.0, 90.0, 78.0, 89.0, 96.0, 75.0, 88.0, 90.0, 96.0], [89.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [90.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [78.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [89.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [96.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [75.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [88.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [90.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [96.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
for(int i = 0; i <10  ; i++){
    for(int j = 0; j <10  ; j++){
      {tests[i][j] = (Double) testScores.get(i*10 +j);
      }
    }

this will work这会起作用

if you want to calculate the mean of the i-th column :如果要计算第 i 列的平均值:

double mean(column_index) {
    double mean = 0;
    for(int i = 0; i <10  ; i++){
        mean = mean + tests[i][column_index];}
    return (mean/10) ;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM