【发布时间】:2014-01-04 17:50:34
【问题描述】:
我是 Java 新手。我想我的代码从用户那里获取一个 max = 100 个整数的数组,然后它应该确定是否有任何重复的整数。如果有重复,它应该打印 NO,如果所有整数都是唯一的,它应该打印 YES。它应该从最低到最高对输入进行排序,然后在排序后打印索引号及其对应的整数。我也可以按顺序获得最终的排序输出。这就是我到目前为止所拥有的。关于如何更好地做到这一点的任何想法?
public static void main(String args[]){
Scanner takeIn = new Scanner(System.in);
System.out.println("Enter the numbers separated by comma's");
String startRay = takeIn.next();
String[] allParts = startRay.split(",");
int L = allParts.length;
int[] intAllParts = new int[allParts.length];
Arrays.sort(allParts);
for(int n=0; n<L; n++){
intAllParts[n] = Integer.parseInt(allParts[n]);
System.out.println(" Index of " + n + " Value of " + allParts[n]);
}
for(int n=1; n<L; n++){
intAllParts[n] = Integer.parseInt(allParts[n]);
if(intAllParts[n-1]==intAllParts[n]){
System.out.println(" First duplicate found at index " + (n));
System.out.println(" NO");
System.out.println(Arrays.toString(allParts) + " Array Values");
return;
}
}
Arrays.sort(allParts);
System.out.println(Arrays.toString(intAllParts) + " Array Values");
System.out.println(" YES");
takeIn.close();
}
}
输出
Enter the numbers separated by comma's
9,6,4,3,22,12,7,8,44,33,21,19,26,48,55,61,15,14,2,61,27,76,79,84,93
Index of 0 Value of 12
Index of 1 Value of 14
Index of 2 Value of 15
Index of 3 Value of 19
Index of 4 Value of 2
Index of 5 Value of 21
Index of 6 Value of 22
Index of 7 Value of 26
Index of 8 Value of 27
Index of 9 Value of 3
Index of 10 Value of 33
Index of 11 Value of 4
Index of 12 Value of 44
Index of 13 Value of 48
Index of 14 Value of 55
Index of 15 Value of 6
Index of 16 Value of 61
Index of 17 Value of 61
Index of 18 Value of 7
Index of 19 Value of 76
Index of 20 Value of 79
Index of 21 Value of 8
Index of 22 Value of 84
Index of 23 Value of 9
Index of 24 Value of 93
First duplicate found at index 17
NO
[12, 14, 15, 19, 2, 21, 22, 26, 27, 3, 33, 4, 44, 48, 55, 6, 61, 61, 7, 76, 79, 8, 84, 9, 93] Array Values
【问题讨论】:
-
您只是将每个值与其前一个值进行比较。您需要做的是,使用嵌套的 for 循环,遍历数组的每个值,然后为每个值再次循环遍历数组,将每个元素与当前元素进行比较。 (但请确保您没有将其与自身进行比较。)
-
@AndrewG 提问者已经在对列表进行排序,因此重复项肯定会彼此相邻。无需进行嵌套循环检查。
-
@ADTC 是的,我在发帖后注意到了这一点。哎呀。 ;)
-
除非代码不符合您的预期,否则最好将其发布到codereview.stackexchange.com
标签: java arrays sorting loops input