S.Mac S.Mac -4 years ago 112
Java Question

Java find three num in array

Task: Given an array of int's, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other, otherwise return false.

This is my current code:

public static boolean contains(int[] arr, int item) {
for (int n : arr) {
if (item == n) {
return true;
}
}
return false;

Answer Source
public static boolean contains(int[] arr, int item) {
    // Count of number of occurences
    int count=0;

    for (int i = 0; i < arr.length; i++) {
    if(arr.length-1 == i){
        if(arr[i] == item)
          count++;
     }else {
        if (arr[i] == item &&  arr[i] + 1 == item)
            return false;
        if(arr[i] == item)
            count++;
           }
        }
       return count == 3;
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download