+ 1

Hi guys... What do I have to do to this program if I want to check if 2 or more elements are in the array. Let's say 12 n 36?

public class Program { public static int idx(int[]arr) { int i = 0; while (i<arr.length) { if(arr[i]==10) return 1; i++; } return -1; } public static void main (String []args){ int[]arr1={12,9,5,2,36,8,54}; System.out.println(idx(arr1)); } }

27th Mar 2017, 6:26 AM
Ricardo Chitagu
Ricardo Chitagu - avatar
2 Answers
+ 2
public class Program { public static int idx(int[] arr, List<Integer> numbers) { int check = 0; for (int i = 0; i < arr.length; i++) { if (numbers.contains(arr[i])) { check++; if (check >= 2) { return 1; } } } return -1; } public static void main(String[] args) { List<Integer> numbers = new LinkedList<Integer>(); numbers.add(10); numbers.add(12); numbers.add(36); int[] arr1 = {12, 9, 5, 2, 10, 36, 8, 54}; System.out.println(idx(arr1, numbers)); } }
27th Mar 2017, 7:20 AM
T0nd3
+ 1
it's supposed to return 1 if an element is available. ryt now it's checking if 10 is available in the while loop which returns -1 but if I try to check for two elements it returns an error.
27th Mar 2017, 6:29 AM
Ricardo Chitagu
Ricardo Chitagu - avatar