2017-02-16 28 views
0
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); 
    } 
} 

这显然不起作用。我曾尝试使用tester.I想知道我应该如何编写构造函数,以便它生成从0到9的随机整数?谢谢。如何在构造函数中使用随机整数填充数组? (2D阵列)

您可以忽略下面的内容。

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(); 
    } 
    } 

    } 

回答

1

您的构造函数只设置2​​d数组中的最后一个值。您将需要像遍历`totalAccidents'函数一样遍历数组,以设置数组中的每个值。所以像这样的东西应该在你的构造函数中:

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