user7479687
user7479687

Reputation:

Build a java program that finds the frequency of a number in a given array

I have a given array with the temperatures of days and I need to build a class that finds out how many days have had the temperature 22°C. Here is what I did:

public class Frequence {
    public static void main(String args[]){
        int arr[] = {20,22,18,19,20,25,27,30,29,29,24,22,16,18,20,23,21,22,26,30,28,29,28,27,26,26,27,23,24,25};
        System.out.println(count);
    }

    public static int frekuenc(int[] arr) {
        int count=0;
        int i=0;

        while(i<arr.length)  {
            if(arr[i]==22) {
                count=count+1;
                i++;
                return count;
            }
        }
    }
}

Upvotes: 0

Views: 320

Answers (2)

Hiccup
Hiccup

Reputation: 616

public class Frequence {

    public static void main(String args[]) {
        int arr[] = { 20, 22, 18, 19, 20, 25, 27, 30, 29, 29, 24, 22, 16, 18, 20, 23, 21, 22, 26, 30, 28, 29, 28, 27,
                26, 26, 27, 23, 24, 25 };
        System.out.println(frekuenc(arr, 22));
    }

    public static int frekuenc(int[] arr, int tempToFind) {
        HashMap<Integer, Integer> countMap = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            Integer temperature = new Integer(arr[i]);
            if (countMap.get(temperature) != null) {
                countMap.put(temperature, countMap.get(temperature) + 1);
            } else {
                countMap.put(temperature, 1);
            }
        }
        return countMap.get(tempToFind);

    }
}

Upvotes: 1

shmosel
shmosel

Reputation: 50716

I'm guessing your code loops infinitely, because i++ is inside the if. Move it to the end of the loop instead. And the return statement should be moved out of the loop altogether. Otherwise it'll return on the first match.

int count = 0;
int i = 0;
while(i<arr.length)  {
    if(arr[i]==22){
        count++;
    }
    i++;
}
return count;

Or you could use a more conventional for loop:

int count = 0;
for (int i = 0; i < arr.length; i++) {
    if(arr[i]==22){
        count++;
    }
}
return count;

Or an enhanced for:

int count = 0;
for (int n : arr) {
    if (n == 2) {
        count++;
    }
}
return count;

Or a stream:

return Arrays.stream(arr)
        .filter(n -> n == 22)
        .count();

Upvotes: 2

Related Questions