Java 数组 : Finding Unique Numbers In A Group of 10 Inputted Numbers

标签 java arrays

我在这里不知所措。

我有这个家庭作业,我必须让用户输入 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++) {

谢谢大家的帮助。

最佳答案

不是输入值数组,而是将它们放在 IntegersSet 中。根据定义,集合仅存储唯一值。如果添加 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/

相关文章:

java - 为什么 Java 编译器不能正确推断继承?

java - 如何使用java创建数组列表

javascript - 将变量传递给数组列表

java - Spring @autowired 不起作用

c++ - 计算二维数组的平均值、最小值、最大值

javascript - 更改两个数组总是同时更改另一个数组

Java:单击 JButton 后图形消失

java - 如何让一个 actionListener 打断另一个

java - Tomcat 7 中的 JNDI 数据源配置

java - 内存不足异常+分析hprof文件转储