我在这里不知所措。
我有这个家庭作业,我必须让用户输入 10 个数字,将它们放在一个数组中,并找出哪些输入的数字是唯一的。
这是我现在的工作流程:输入数字>如果之前没有输入数字,则存储在数组中;如果之前输入过数字,则忽略>显示输入的数字>显示唯一数字
例如:输入 1 2 3 5 1 2 4 6 会找到唯一的数字并显示“1 2 3 4 5 6”
到目前为止,我的代码如下所示:
public class HwChapter6 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] count = new int[10];
int number = 0;
int x = 0;
boolean unique = false;
int length = count.length;
System.out.println("Insert 10 single digit numbers in any order your heart desires:");
for (int i = 0; i < count.length; i++) {
count[i] = input.nextInt();
number = count[i];
for (int j = 0; j < count.length; j++) {
谢谢大家的帮助。
最佳答案
不是输入值数组,而是将它们放在 Integers
的 Set
中。根据定义,集合仅存储唯一值。如果添加 3 个 'foo',集合中将只有一个 'foo'。
// Add this to your top-level loop
Set<Integer> uniqueValues = new TreeSet<Integer>;
uniqueValues.add(number);
// Add this after the loop to write all unique values on one line
for (Integer value : uniqueValues) {
System.out.print(value.toString() + " ");
}
// Now end the line.
System.out.println();
关于Java 数组 : Finding Unique Numbers In A Group of 10 Inputted Numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885162/