java—从用户输入的两个数组中获取两个数组的公共值的输出

jyztefdp  于 2021-06-29  发布在  Java
关注(0)|答案(4)|浏览(423)

我对java还是个新手,一直在尝试编写接受两个不同的公共值数组并输出这两个数组的公共值的代码,但我不断收到以下错误消息:
线程“main”中的异常您的公共值是:0您的公共值是:0您的公共值是:0您的公共值是:0 java.lang.arrayindexoutofboundsexception:索引5超出homworktestingq.main(homworktestingq)中长度5的界限。java:18)

Scanner sc = new Scanner(System.in);{       
            int n = 5;
            int m = 5;
            int[] array1 = new int[m];
            int[] array2 = new int[n];  

            System.out.println("Enter the first array: ");
            n=sc.nextInt();
            System.out.println("Enter the second array");
            m=sc.nextInt();
            for(int i = 0; i < array1.length; i++) {
                for(int j = 0; i < array2.length; j++) {
                    if(array1[i] == array2[j]) {
                        System.out.println("Your common values are: " + array1[i+j] );
                    }
                }
            }
        }
    }
}
1cklez4t

1cklez4t1#

我修正你的密码:

Scanner sc = new Scanner(System.in);

        int n = 5;
        int m = 5;
        int[] array1 = new int[m];
        int[] array2 = new int[n];

        System.out.println("Enter the first array: ");
        for (int i = 0; i < n; i++) {
            array1[i] = sc.nextInt();
        }
        System.out.println("Enter the second array");
        for (int i = 0; i < n; i++) {
            array2[i] = sc.nextInt();
        }
        for (int item : array1) {
            for (int value : array2) {
                if (item == value) {
                    System.out.println("Your common values are: " + item);
                }
            }
        }
zz2j4svz

zz2j4svz2#

第一个问题
当您扫描的值时,数组的大小不会改变 m 以及 n 因为java是传递值,数组的大小是值,而不是变量。
所以你应该这样做-

int m = scanner.nextInt();
int[] arr = new int[m];

第二个问题

System.out.println("Your common values are: " + array1[i+j] );

这将超出界限,也许你应该这样做-

System.out.println("Your common values are: " + array1[i] );
jdzmm42g

jdzmm42g3#

我认为问题在于您在这里添加了数组迭代器:

array1[i+j]

i+j的加法大于数组1的长度。
另一方面,您的数组没有按照我认为您所期望的那样进行填充,原因是:

System.out.println("Enter the first array: ");
        n=sc.nextInt();
        System.out.println("Enter the second array");
        m=sc.nextInt();

我只是在猜测,也许你还有更多的工作要做。

7cwmlq89

7cwmlq894#

你不需要把指数加起来。。因为array1[i]等于array2[j],所以打印任意一个:

for(int i=0;i<array1.length;i++){
    for(int j=i+1;j<array2.length;j++){
        if(array1[i]==array2[j]) int commonValue = array1[i];
        return commonValue; // or print it
    }    
}

相关问题