0
What's wrong with my code? I'm trying to find the least frequent number in an array.
public class Antimode { public static void main(String[] args) { int[] arr = { 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 6, 6, 7, 7, 9, 9, 10}; System.out.println("The antimode is " + antimode(arr)); } public static int antimode(int[] arr) { int minNum = 0; int Appearances = 100; for (int counter = 0; counter < arr.length; counter++) { int count = 0; for (int x = 0; x < arr.length;) { if (arr[counter] == arr[x]) count++; if (count < Appearances) { minNum = arr[counter]; Appearances = count; } return minNum; } } return -1; } }
6 Answers
+ 2
I might have explaint it poorly.
Take a look
https://code.sololearn.com/cFKyUp8PkHxO/?ref=app
+ 2
The problem is the return statement.
When return gets executed the function will return a valiue and closes. That is why your code always returns 2.
You can check it by putting a System.out.println in one of the loops.
In your case the return statement should be outside of both loops.
0
Michael F, when I move the return statement outside of the loops the variable minNum isnât recognized
0
return minNum should be where return -1 is right now.
Also x is never incremented in the 2nd for loop.
and another problem is the (count < Appearances) condition. You should compare the counter with the current min appearence after you compared one number with the whole array. So this condition should be inside the first loop but AFTER the scond loop.
0
I changed the placement of the return statement and it doesn't display anything.
0
Thank you very much Michael F!