基本数组 - Java

时间:2016-01-14 23:14:06

标签: java arrays

我需要创建两个名为A和B的数组,两个类型都是int,大小为100.每个索引应该是一个介于0和100之间的随机数,然后比较两个数组,并说出相同数字的2的两倍出现在两个阵列中。

这是我到目前为止所拥有的

int count = 0;

int [] A = new int [100];
int [] B = new int [100];

for(int i = 0; i < A.length; i++){
    A [i] = (int)(Math.random()*101);
    System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
    B [i] = (int)(Math.random()*101);
    System.out.println("Array B: " + i);
}

if(A [i] == B [i]){
    count++;
}

我不知道如何显示两个数组中出现了多少次相同数字。

3 个答案:

答案 0 :(得分:1)

你需要遍历两个数组:

int count = 0;

int [] A = new int [100];
int [] B = new int [100];

for(int i = 0; i < A.length; i++){
    A [i] = (int)(Math.random()*101);
    System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
    B [i] = (int)(Math.random()*101);
    System.out.println("Array B: " + i);
}

// Loop through the first array
for(int i = 0; i < A.length; i++) {
    // For each element in the first array, loop through the whole second one
    for (int j = 0; j < B.length; j++) {
        // If it's a match
        if(A[i] == B[j])
            count++;
    }
}

System.out.println("Count: " + count);

答案 1 :(得分:1)

或者,如果您不需要2个数组,则可以执行以下操作:

int count = Random.ints(100, 0, 101).boxed().collect(toSet())
                  .retainAll(Random.ints(100, 0, 101).boxed().collect(toSet()))
                  .size();

答案 2 :(得分:0)

你开始很好,但你需要一个嵌套的for循环来检查每个索引。

另外 - 确保在数组中打印出A [i]和B [i],否则你只是打印出索引号而不是索引中的数字。

success function

希望发布正确...首次在本网站上发布代码,但我希望我有所帮助!

请记住,如果两次发布相同的号码,您将获得超过100的数量。

祝你好运!