我是java新手。我希望我的代码从用户处获取 max = 100 个整数的数组,然后它应该确定是否存在重复的整数。如果有重复,则应打印“否”;如果所有整数都是唯一的,则应打印"is"。它应该从最低到最高对输入进行排序,然后在排序后打印索引号及其相应的整数。我也可以按顺序获得最终的排序输出。这是我到目前为止所拥有的。关于如何做得更好有什么想法吗?
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
最佳答案
只需使用TreeSet
即可:
public static void main(String[] args) throws Exception {
final String in = "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";
final SortedSet<Integer> inputs = new TreeSet<>();
boolean dup = false;
for (final String s : in.split(",")) {
if (!inputs.add(Integer.parseInt(s))) {
dup = true;
}
}
if (dup) {
System.out.println("There were duplicates");
} else {
System.out.println("There were no duplicates");
}
System.out.println("The highest number is " + inputs.last());
System.out.println("The lowest number is " + inputs.first());
final Iterator<Integer> iter = inputs.iterator();
for (int i = 0; iter.hasNext(); ++i) {
System.out.println(i + " -> " + iter.next());
}
}
Set
保证项目唯一,如果该项目已在 Set
中,add
将返回 false
。
SortedSet
保证 Set
中的所有项目始终排序,TreeSet
是 SortedSet
的实现。
首先,循环遍历输入 String
并已被 ,
分割,并将项目添加到 Set
中并检查返回值。然后我们打印出是否发现了重复项。
然后使用 last
和 first
方法来获取最大和最小元素。
最后,使用其Iterator
循环遍历Set
,以按顺序吐出元素及其索引。请注意,Set
没有索引元素,因此这些是“伪”索引。
关于java - 扫描仪输入数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924481/