-1

given an array of int is there a way to do membership test to see if a particular number is present in the int array. the question was to do find missing number between 1-10 given by user. eg [1,2,3,4,5] if 1 is in array it should give true. I cant seem to post my code here.

import java.util.Scanner; 
import java.util.Arrays; 

public class Q1 { 
  public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    System.out.println("Enter numbers of element: "); 
    int size = scan.nextInt(); 
    int arry[]=new int[size]; 
    for(int i =0;i<size;i++){ 
      System.out.println("Enter any number betweent 1-10:"); 
      int element = scan.nextInt(); 
      arry[i] = element; 
    } 
    System.out.println(Arrays.toString(arry)); 
    System.out.println(Arrays.asList(arry).contains(1)); 
  } 
} 
Stultuske
  • 9,296
  • 1
  • 25
  • 37

2 Answers2

0

The problem with this code is that Arrays.asList will create List<int[]> NOT the implied List<Integer>, therefore method .contains(1) is always false.

Simple method should be implemented to check the membership:

static boolean isInArray(int n, int ... arr) {
    for (int x : arr) {
        if (x == n) return true;
    }
    return false;
}

Using Stream API:

static boolean isInArray(int n, int ... arr) {
    return Arrays.stream(arr).anyMatch(x -> x == n);
}

Or the input array should be declared as Integer[] arry, then Arrays.asList provides appropriate List<Integer>, and method contains(1) is applicable to such list.

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

Try streams. I don't think aslist().contains() supports primitives like int. This works though:

import java.util.stream.IntStream;

class Main {  
public static void main(String args[]) { 
    int[] a = {1,2,3,4,5,7,8,9};
    int find_1 = 4;
    int find_2 = 6;
    boolean find_num1 = IntStream.of(a).anyMatch(x -> x == find_1);
    boolean find_num2 = IntStream.of(a).anyMatch(x -> x == find_2);
    System.out.println("First num in array? " + find_num1);
    System.out.println("Second num in array? " + find_num2);
    } 
}
Odj fourth
  • 649
  • 1
  • 9
  • 16