-2

I have to display that given number present in array or not. For example:

int[] number1 = {2,3,6,14,23,8,23,19};   
int[] numbers2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};

Now I have to check whether number1 array element present in number2 array or not if yes then print present number. So how can I achieve this in Java?

My code:

int[] number1 = {2,3,6,14,23,8,23,19};   
    int[] numbers2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};

for(int i=0; i<number2.length;i++){
    for(int j =0; j<number1.length:j++){
        if(number2[i]==number1[j]){
            System.out.println("present number is:"+number1[i]);
        }
    }
}
Renats Stozkovs
  • 2,549
  • 10
  • 22
  • 26
Gaurav Takte
  • 607
  • 5
  • 22

4 Answers4

3

A nested for loop will help you to achieve that, basically for each number in number1, you need to traverse numbers2 to see if the value is present.

for(int i: number1) {
        for(int j: numbers2) {
            if(i == j) {
                System.out.println(i);
                break; //exit the inner loop if the number is present
            }
        }
    }
Jie Heng
  • 196
  • 4
1

This is the basic idea

  1. Iterate through the first array using a for loop.
  2. Use an inner for loop to iterate through the elements of second array and keep comparing the value.
  3. If the value is found, print it and break out of inner loop.
Pooja Arora
  • 574
  • 7
  • 19
1

Change i --> j at System.out.println("present number is:"+number1[j]);

gifpif
  • 4,507
  • 4
  • 31
  • 45
0

It's simple and clean when using Java 8.

int[] number1 = {2,3,6,14,23,8,55,23,19};
int[] numbers2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};

Arrays.stream(numbers2)
        .filter(num -> Arrays.stream(number1).anyMatch(e -> e == num))
        .forEach(System.out::println);
sovas
  • 1,508
  • 11
  • 23