繁体   English   中英

如何在构造函数中用随机整数填充数组? (二维数组)

[英]How do you fill in an array with random integers in the constructor? (2D array)

import java.util.Random;
public class Accidents{
    static final int DAYS  = 31;
    static final int HOURS = 24;

    private int[][] accidents = new int[DAYS][HOURS];

    public Accidents(){
        Random rand = new Random();
        accidents[DAYS][HOURS] = rand.nextInt(10);
    }
}

这显然行不通。 我试过使用测试器,我想知道如何编写构造函数,以便它生成0到9之间的随机整数? 谢谢。

您可以忽略下面的内容。

  public int totalAccidents(){
     int total = 0;
     for(int i=0; i<accidents.length; i++){
        for(int j=0; j<accidents[0].length; j++){
           total += accidents[i][j]; 
        }
     }
        return total;     
  }


  public int mostAccidents(){
  int sum = 0;
  int max = 0;
     for (int i=0;i<24;i++){
        for(int j=0; j<accidents.length; j++){
        sum += accidents[j][i];
        }
        if (sum> max)
           max = sum;
     }
     return max;
  }


  public void printArray(){
     for(int j=0; j<accidents.length; j++){
        for(int k=0; k<accidents[0].length; k++){
           System.out.print(accidents[j][k]+"   ");
        }
        System.out.println();
     }
  }

  }

您的构造函数仅设置2d数组中的最后一个值。 您将需要像在“ totalAccidents”函数中那样遍历数组,以设置数组中的每个值。 所以这样的事情应该在您的构造函数中:

for(int i=0; i<accidents.length; i++){
    for(int j=0; j<accidents[0].length; j++){
       accidents[i][j] = rand.nextInt(10);
    }
  }

暂无
暂无

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

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