ArrayIndexOutOfBoundsException Java问题

时间:2015-04-28 05:02:44

标签: java

所以我一直在研究这个问题。我不断得到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;
    }
}

2 个答案:

答案 0 :(得分:1)

我认为问题在于

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

i < list_1.length + 1j < 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 + 1list_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

答案 1 :(得分:1)

在你的迭代(compareLists)中,你应该使用'length'(不是length + 1)

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