I'm trying to write a method that accepts an array of integers and returns the number of unique values in that array. For example, for array {5, 6, 5, 7, 5, 7} the method returns 3 because there are 3 duplicates (5,5,7). I'm not sure where I went wrong, I tried creating a variable list
so that when I call numUnique(list)
it would give me my answer, but that didn't seem to work. Any suggestions?
Code:
import java.util.Scanner;
public class Unique_Values {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] list = new int[n];
System.out.printf("%d%n ", list);
}
public static int numUnique(int[] list) {
if (list.length == 0) {
return 0;
} else {
int count = 1;
for (int i = 1; i < list.length; i++) {
if (list[i] != list[i - 1]) {
count++;
}
}
return count;
}
}
}