首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java:打印出数组中的每个数字,而不打印该数字的重复?

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

Stack Overflow用户
提问于 2018-09-16 07:14:27
回答 1查看 86关注 0票数 0

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

每次我这样做时,要么只打印不重复的数字,在本例中为{6,2,1},要么全部打印。然后我没有按照作业建议的方式做

赋值要求我在将一个值放入数组之前检查数组,看看它是否在那里。如果不是,则添加它,但如果是,请不要添加。

现在,我只是不断得到超出边界的错误,或者它只是打印所有的东西。

我该怎么做有什么建议吗?

代码语言:javascript
复制
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");
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-09-16 07:39:40

如果顺序不重要,可以使用长度为10的help数组来实现。

代码语言:javascript
复制
    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 + " ");
        }
    }
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52349636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档