Java:打印出数组中的每个数字,而不打印其重复的数字吗?

时间:2018-09-15 23:14:27

标签: java arrays

我正在尝试打印一个数组,但仅打印出该数组中的不同数字。 例如:如果数组具有{5,5,3,6,3,5,2,1} 那么它将打印{5,3,6,2,1}

每次执行此操作时,要么只打印非重复数字(在此示例中为{6,2,1}),要么全部打印它们。然后我没有按照作业建议的方式

任务要我在将值放入数组之前先检查它是否在其中。如果不是,则添加它,但如果不添加。

现在我只是一直越界错误,否则它只会打印所有内容。

关于我应该做什么的任何想法

import java.util.Scanner;

public class DistinctNums {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        int value;              
        int count = 0;  
        int[] distinct = new int[6];

        System.out.println("Enter Six Random Numbers: ");
        for (int i = 0; i < 6; i++) 
        {
            value = input.nextInt(); //places users input into a variable 
        for (int j = 0; i < distinct.length; j++) {
            if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
            {
                distinct[count] = value; // if its not equal then place it in array
                count++; // increase counter for the array
            }
        }
        }

        // Displays the number of distinct numbers and the  
        // distinct numbers separated by exactly one space
        System.out.println("The number of distinct numbers is " + count);
        System.out.print("The distinct numbers are");
        for (int i = 0; i < distinct.length; i++)
        {
            System.out.println(distinct[i] + " ");

        }
        System.out.println("\n");
    }
}

2 个答案:

答案 0 :(得分:0)

始终记住-如果您想要元素的单个副本,则需要使用 set 。 Set是不同对象的集合。

在Java中,您有一个称为HashSet的东西。如果要保留订单,请使用LinkedHashSet。

int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();

//add all the elements into set
for(int number:intputArray) {
    set.add(number);    
}
for(int element:set) {
    System.out.print(element+" ");
}

答案 1 :(得分:-1)

如果顺序不重要,则可以使用长度为10的帮助数组进行设置。

    int [] intputArray = {5,5,3,6,3,5,2,1};
    int [] helpArray = new int[10];

    for(int i = 0; i < intputArray.length ; i++){
        helpArray[intputArray[i]]++;
    }

    for(int i = 0; i < helpArray.length ; i++){
        if(helpArray[i] > 0){
            System.out.print(i + " ");
        }
    }