我正在尝试编写一个接受整数数组并返回该数组中唯一值数的方法。例如,对于数组{5,6,5,7,5,7},该方法返回3,因为有3个重复项(5,5,7)。我不确定我出错的地方,我尝试创建一个变量list
,这样当我打电话给numUnique(list)
时,它会给我我的答案,但这似乎不起作用。有什么建议么?查找用户输入数组中唯一值的数
代码:
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;
}
}
}
“似乎并没有工作“并不是一个明确的问题描述。你的意见是什么?你期望输出什么? – shmosel
您的方法只检查相邻的重复项。 – shmosel
你需要一个内部循环。你只是在数字之前直接检查元素,例如:'4545'你比较'5'到'4'而不是'5'到'5'。您需要将数组中的每个数字与所有其他数字进行比较。你可以使用内部循环来做到这一点...... – brso05