填充数组java后忽略其他参数

时间:2018-10-14 19:12:43

标签: java arrays methods

代码:

//takes in the parameters by int and string and builds an array
public void setParameter(int newParameterNum, String newParameterName) {

    this.parameterNum = newParameterNum;

    this.parameterName = newParameterName;

    this.parameterList = new String[numParameters];

    this.parameterList[parameterNum] = parameterName;

    for (int i = 0; i < numParameters; i++) {

         this.countParameter += i;
    }


}

主要代码(无法编辑):

//Add the needed parameters, Report should make sure I am not trying to break it
    report1.setParameter(0, "01/01/1970");
    report1.setParameter(1, "01/01/2018");
    report1.setParameter(2, "pjdt");

错误:

run: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2   at
     

week6project.Report.setParameter(Report.java:134)在   week6project.Week6Project.main(Week6Project.java:34)   C:\ Users \ nicho \ AppData \ Local \ NetBeans \ Cache \ 8.2 \ executor-snippets \ run.xml:53:   Java返回:1个BUILD FAILED(总时间:0秒)

那么,如何忽略不想添加到数组的参数呢?如果请求的参数数量小于传递的参数。

即请求2 parameters,但在这种情况下通过了3

The numParameters is updated through this method:
public void setNumParameters(int newNumParameters) {

    this.numParameters = newNumParameters;

}

设置的主要方法:

 //Set the number of parameters for each report
    report1.setNumParameters(2);
    report2.setNumParameters(4);

1 个答案:

答案 0 :(得分:0)

当尝试使用java.lang.ArrayIndexOutOfBoundsException访问数组元素时,收到错误index>= array.length

在下面的代码行中,确保0 <= parameterNum < numParameters

this.parameterList[parameterNum] = parameterName;