得到错误抱怨我的数组大小

时间:2013-11-16 10:18:34

标签: java arrays eclipse loops size

这是我的代码:

import java.util.Scanner;

public class Programming_Exercise_27 {

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        int[] list1 = new int[3];
        int[] list2 = new int[3];

        System.out.println("Enter 3 numbers for list1: ");


        for (int i = 0; i < list1.length; i++){
            list1[i] = input.nextInt();
        }

        System.out.println("Enter 3 numbers for list2: ");

        for (int i = 0; i < list2.length; i++){
            list2[i] = input.nextInt();
        }

        if(equal(list1, list2) == true){

            System.out.println("The two lists are identical");
        }

        else{

            System.out.println("The two lists are not identical");
        }
    }


    public static boolean equal(int[] list1, int[] list2){

        boolean decision = true;
        int hold;
        int check = 0;
        int check2 = 0;

        for (int i = 0; i < list1.length; i++){

            hold = list1[i];

            for (int x = 0; i < list1.length; x++){

                if (list1[x] == hold){

                    check++;
                }
                else { /* do nothing */ }

            }

            for (int y = 0; i < list2.length; y++){

                if (list2[y] == hold){

                    check2++;
                }
                else{ /* do nothing */ }

            }

            if (check != check2){

                decision = false;
                break;
            }
            else{

                check = 0;
                check2 = 0;
                hold = 0;
            }
        }


        return decision;
    }


}

我想要做的是用相同的方法来计算数组中某个数字的出现次数。如果数组中的每个数字相等,则表示它们是相同的。但由于某种原因,我一直遇到阵列大小问题。请帮忙。

1 个答案:

答案 0 :(得分:4)

这一行

for (int x = 0; i < list1.length; x++){

在条件中应该有x而不是i,否则x将继续增加,直到list1[x]在数组末尾运行。同样,这一行

for (int y = 0; i < list2.length; y++){

应该有y而不是i