Java中的2D数组,带有数字操作

时间:2014-02-19 14:31:59

标签: java arrays multidimensional-array

我的目标是

  1. 创建一个5x5数组,并使用1到25范围内的随机整数填充它。
  2. 打印此原始数组
  3. 处理数组,计算几率,均数和求和数组中所有元素的总和。
  4. 打印总赔率,平均值和总和。
  5. 我不知道怎么做,我的老师非常困惑,无法帮助我。我想知道我是否能得到一些指导。

    这是我的代码:

    public class Processing {
        public static void main(String[] args) {
            Random Random = new Random();
            int[][] Processing = new int[5][5];
            for (int x = 0; x < 5; x++) {
                int number = Random.nextInt(25);
                Processing[x] = number;
            }
            for (int i = 0; i < 5; i++) {
                Processing[i] = new int[10];
            }
        }
    }
    

1 个答案:

答案 0 :(得分:2)

请遵循变量的命名约定。见这里:http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java

无论如何,你必须按如下方式嵌套你的循环:

for(int i = 0; i < 5; i ++) {
   for(int j = 0; j < 5; j++) {
        yourArray[i][j] = random.nextInt(25);
   }
}

i是行号,j是列号,因此这会为一行中的每个元素指定值,然后转到下一行。

我猜这是作业,所以我不会只是给出你的其他问题的答案,但为了让你走上正轨,这里是你打印元素的方法。再次,使用两个嵌套循环:

for(int i = 0; i < 5; i ++) {
   for(int j = 0; j < 5; j++) {
        // print elements in one row in a single line
        System.out.print(yourArray[i][j] + " ");
   }
   System.out.println();  //return to the next line to print next row.
}