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; } }

5th Aug 2019, 11:04 PM
Dreon Wheatley Owens
Dreon Wheatley Owens - avatar
6 odpowiedzi
+ 2
I might have explaint it poorly. Take a look https://code.sololearn.com/cFKyUp8PkHxO/?ref=app
6th Aug 2019, 3:56 PM
Michael F
Michael F - avatar
+ 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.
6th Aug 2019, 4:08 AM
Michael F
Michael F - avatar
0
Michael F, when I move the return statement outside of the loops the variable minNum isn’t recognized
6th Aug 2019, 2:12 PM
Dreon Wheatley Owens
Dreon Wheatley Owens - avatar
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.
6th Aug 2019, 3:28 PM
Michael F
Michael F - avatar
0
I changed the placement of the return statement and it doesn't display anything.
6th Aug 2019, 3:36 PM
Dreon Wheatley Owens
Dreon Wheatley Owens - avatar
0
Thank you very much Michael F!
6th Aug 2019, 4:23 PM
Dreon Wheatley Owens
Dreon Wheatley Owens - avatar