William Pfaffe William Pfaffe - 2 months ago 10
Java Question

Won't skip if number already exists in array?

I am currently trying to make a method, that displays the amount of times, a number exists within a array.

My method is:

public void freq(int[] arr) {
Arrays.sort(arr);
String output = "";
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (this.helper(arr[i]) == true) {
i++;
} else if (this.helper(arr[i]) == false) {
for (int k : arr) {
if (k == arr[i]) {
count++;
}
}
System.out.println("Number of instances to: " + arr[i] + " : " + count);
count = 0;
}
}
}


The helper class is used to check if the number it's about to check, already has been checked. I am using a arraylist to store the numbers that are already checked:

private List<Integer> existingInt = new ArrayList<Integer>();


The method helper is written:

public boolean helper(int i) {
boolean alreadyExists = false;
for (int k : existingInt) {
if (i == k) {
alreadyExists = true;
return alreadyExists;
} else {
existingInt.add(i);
alreadyExists = false;
return alreadyExists;
}
}
return alreadyExists;
}


Helper returns a boolean, true or false, if the number exists. I thereafter check, in a if statement, if it returns true or false. If true, then i skip (or atleast try to) with:

if (this.helper(arr[i]) == true) {
i++;
}


In short, my method counts the number of occurances in a array of integers. What it doesn't do, is skip the check, if my helper method returns a true.

Answer

Since you're sorting the array you could do this

    for (int i = 0; i < arr.length;) {
        int count = 1;
        int num = arr[i];
        while(++i < arr.length && arr[i] == num) {
            count++;
        }
        System.out.println("Number of instances to: " + num + " : " + count);
    }
Comments