数组 - 超出随机数的范围

时间:2014-09-07 04:19:56

标签: java

我有以下名为Clinica

的课程
import java.util.Random;

public class Clinica {
    //atributos
    private int[][] calendariosEnf;
    private int[][] calendariosMed;

    //Constructor
    public Clinica(){
        calendariosEnf = new int[12][31];
        calendariosMed = new int[12][31];
    }

    //Sets y gets
    //Calendario para las enfermeras
    public void setCalendariosEnf(int[][] calendariosEnf){
        this.calendariosEnf = calendariosEnf;
    }
    public int[][] getCalendariosEnf(){
        return calendariosEnf;
    }

    //Calendario para los medicos
    public void setCalendariosMed(int[][] calendariosMed){
        this.calendariosMed = calendariosMed;
    }
    public int[][] getCalendariosMed(){
        return calendariosMed;
    }

    Listas lista1 = new Listas();
    public void agregarCalEnf(){
        Random rand = new Random();
        int min = 1;
        int max = 5;
        for(int m = 0; m < 11; m++){
            for(int d = 0; d < 30; d++){
                int randomNum = rand.nextInt((max - min) + 1) + min;
                calendariosEnf[d][m] = randomNum;
            }
        }
    }   
}

如果我尝试打印一个文件,例如calendariosEnf[1][4],我会收到以下消息

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12

任何人都可以帮我解决索引错误的问题吗?

我创建了Prueba类,以检查程序是否正常工作......

public class Prueba {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Listas list = new Listas();
        Clinica clin = new Clinica();
        list.agregarMedicos();
        clin.agregarCalEnf();
        System.out.println(clin.getCalendariosEnf()[1][4]);
    }
}

1 个答案:

答案 0 :(得分:2)

      for(int m = 0; m < 11; m++){
            for(int d = 0; d < 30; d++){
                int randomNum = rand.nextInt((max - min) + 1) + min;
                calendariosEnf[d][m] = randomNum;
            }
        }

d不能大于11,否则超出界限。

m可以是0到11(包含),d可以是0到30(包含)。

    for(int m = 0; m < 12; m++){
            for(int d = 0; d < 31; d++){
                int randomNum = rand.nextInt((max - min) + 1) + min;
                calendariosEnf[m][d] = randomNum;
            }
        }