arrayindexoutofboundsexception java问题

rqdpfwrv  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(280)

所以我已经研究这个问题有一段时间了。我一直在找工作 ArrayIndexOutOfBoundsException 但我无法找到问题所在。如果有人能给我指出正确的方向,我会非常感激的!谢谢!

public class Answer {   

    public static void main(String[] args){
        double[] y = {23, 11.1, 50.4};
        double[] x = {22.2, 46, 100.0};
        Answer answer = new Answer();
        answer.answer(y, x);
    }
    public static int answer(double[] y, double[] x) { 
        int result = 0;
        double percent_1, percent_2;
        double[] compareList_1 = new double[x.length];
        double[] compareList_2 = new double[y.length];

        // Calculate percent of first 2 x value array items with y
        // all y values. Store the results in a seperate list.
        for(int i = 0; i < x.length; i++){
            percent_1 = compare(y[i], x[0]);
            percent_2 = compare(y[i], x[1]);
            compareList_1[i] = percent_1;
            compareList_2[i] = percent_2;
        }
        // Compare those lists to find common number
        // There you have your answer.
        result = (int)compareLists(compareList_1, compareList_2);
        return result;
    }
    // Calculates percentage from x and y values
    public static double compare(double y, double x){
        double result = 1 - (y/x);
        return result;
    }
    // Finds common value in lists
    public static double compareLists(double[] list_1, double[] list_2){
        for(int i = 0; i < list_1.length + 1; i++){
            for(int j = 0; j < list_2.length + 1; j++){
                if(list_1[i] == list_2[j]){
                    return list_1[i];
                }
            }
        }
        // Just cus this shouldn't ever return.
        return 100;
    }
}
pbpqsu0x

pbpqsu0x1#

在迭代(comparelists)中,应该使用“length”(而不是length+1)

for(int i = 0; i < list_1.length; i++)
   for(int j = 0; j < list_2.length; i++)
dsf9zpds

dsf9zpds2#

我想问题出在

for(int i = 0; i < list_1.length + 1; i++){
            for(int j = 0; j < list_2.length + 1; j++){
``` `i < list_1.length + 1` 或者 `j < list_2.length + 1` 把它改成

for(int i = 0; i < list_1.length; i++){
for(int j = 0; j < list_2.length ; j++){

删除 `+1` 从每一个条件 `j < list_2.length + 1` 这个 `list_2.length` 会给你数组的长度 `lastIndex +1` 你正在添加另一个 `+1` 使循环条件 `j<lastIndex +1` 在行中循环的最后一次迭代中给出索引错误 `if(list_1[i] == list_2[j]){` 为了 `list_2[j]` 同样在answer方法中,声明数组的依据是

double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];

在循环中,你迭代到 `x.length` 如果 `x.length` 大于 `y.length` 您可以在中获取索引错误 `compareList_2[i] = percent_2;` (在环内)因为它的长度是 `y.length` .

相关问题