java 在数组中打印不同的整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/674618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:20:49  来源:igfitidea点击:

Printing distinct integers in an array

javaarraysduplicates

提问by ???

I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.

我正在尝试编写一个小程序,打印出数组中不同的数字。例如,如果用户输入 1、1、3、5、7、4、3,程序将只打印出 1、3、5、7、4。

I'm getting an error on the else if line in the function checkDuplicate.

我在函数的 else if 行遇到错误checkDuplicate

Here's my code so far:

到目前为止,这是我的代码:

import javax.swing.JOptionPane;

public static void main(String[] args) {
    int[] array = new int[10];
    for (int i=0; i<array.length;i++) {
        array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
                                  + "an integer:"));
    }
    checkDuplicate (array);
}

public static int checkDuplicate(int array []) {
    for (int i = 0; i < array.length; i++) {
        boolean found = false;
        for (int j = 0; j < i; j++)
            if (array[i] == array[j]) {
                found = true;
                break;
            }
        if (!found)
            System.out.println(array[i]);
    }
    return 1;
}
}

回答by jjnguy

The simplest way would be to add all of the elements to a Set<Integer>and then just print the contents of the Set.

最简单的方法是将所有元素添加到 a 中Set<Integer>,然后只打印Set.

回答by MartinStettner

First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").

首先,“ else if”语句是不正确的,因为你没有为if提供任何条件(如果你想要一个if,你需要写“ if (condition) ...”)。

Second, you cannot decide inside the innerloop, if a value should be printed: The way your code works you write a value array[i] for each value array[j]that is different from array[i]!

其次,您无法在内循环决定是否应该打印一个值:您的代码的工作方式是为每个不同于 array[i] 的值 array[j]编写一个值array[i]!

Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.

第三:内部循环只需要从 0 到外部索引i-1:对于每个元素,您只需要决定它是否是第一次出现(即相同的值是否出现在任何先前的索引处)。如果是,打印出来,如果不是,忽略它。

A proper implementation of CheckDuplicate()would be:

的正确实现CheckDuplicate()是:

public static void checkDuplicate(int array []) {
  for (int i = 0; i < array.length; i++) {
    boolean found = false;
    for (int j = 0; j < i; j++)
      if (array[i] == array[j]) {
        found = true;
        break;
      }
    if (!found)
      System.out.println(array[i]);
  }
}

But of course, some kind of Setwould be much more efficient for bigger arrays...

但是,当然,Set对于更大的阵列,某种方式会更有效......



EDIT: Of course, mmyers(see comments) is right by saying, that since CheckDuplicate()doesn't return any value, it should have return type void(instead of int). I corrected this in the above code...

编辑:当然,mmyers(见评论)是正确的,因为CheckDuplicate()不返回任何值,它应该有返回类型void(而不是int)。我在上面的代码中更正了这个......

回答by Nikhil Chelliah

Put them in a set ordered by insertion time, then convert back to an array if necessary.

将它们放入按插入时间排序的集合中,然后在必要时转换回数组。

new LinkedHashSet<Integer>(array).toArray()

回答by Kevin Crowell

Try throwing all of the integers into a Set. Duplicates will not ever be added to the Set and you will be left will a set of unique integers.

尝试将所有整数放入 Set 中。重复项永远不会添加到集合中,您将留下一组唯一的整数。

回答by javashlook

What you want can be accomplished using Java collection API, but not exactly as an one-liner, due to fact collection methods work with Objects and not primitives. J2SE lacks methods that convert, say, int[]to Integer[], but Apache Commons Lang librarycontains such useful methods, like ArrayUtils.toObject()and ArrayUtils.toPrimitive().

您可以使用 Java 集合 API 来完成您想要的操作,但并不完全是单行的,因为事实上集合方法适用于Objects 而不是原语。J2SE 缺少转换方法,例如,转换int[]Integer[],但 Apache Commons Lang包含此类有用的方法,如ArrayUtils.toObject()ArrayUtils.toPrimitive()

Using them, method to remove duplicated elements from an integer array looks something like this:

使用它们,从整数数组中删除重复元素的方法如下所示:

public static int[] removeDuplicates(int... array) {
    Integer[] ints = ArrayUtils.toObject(array);
    Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(ints));
    return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}

If your application is likely to include more of array/collection manipulation, I suggest you take a look at that library, instead of implementing things from scratch. But, if you're doing it for learning purposes, code away!

如果您的应用程序可能包含更多的数组/集合操作,我建议您查看该库,而不是从头开始实现。但是,如果您是出于学习目的而这样做,请远离代码!

回答by monksy

Either use a Set as other people have suggested or use an List compatible class. With a list compatible class just use the Contains method to check if it already exists in the array.

使用其他人建议的 Set 或使用 List 兼容类。对于列表兼容类,只需使用 Contains 方法检查它是否已存在于数组中。

回答by Bill the Lizard

It would probably be better to add each number to a Setimplementation rather than an array. Sets are specifically for storing collections of elements where you want to filter out duplicates.

将每个数字添加到Set实现而不是数组可能会更好。集合专门用于存储要过滤掉重复项的元素集合。

回答by chathura Gawarammana

import java.util.Scanner; public class PrintDistinctNumbers {

导入 java.util.Scanner; 公共类 PrintDistinctNumbers {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int [] numberArray = createArray();
    System.out.println("The number u entered are:   ");
    displayArray(numberArray);
    getDistinctNumbers(numberArray);
}

public static int[] createArray() {
    Scanner input = new Scanner(System.in);
    int [] numberCollection = new int [10];
    System.out.println("Enter 10 numbers");

    for(int i = 0; i < numberCollection.length; i++){
        numberCollection[i] = input.nextInt();
    }
    return numberCollection;

}

public static void displayArray(int[] numberArray) {
    for(int i = 0; i < numberArray.length; i++){
        System.out.print(numberArray[i]+" ");
    }
}

public static void getDistinctNumbers(int[] numberArray) {
    boolean isDistinct = true;
    int temp = 0;
    int [] distinctArrayNumbers = new int [10];
    for ( int i = 0; i < numberArray.length; i++){
        isDistinct = true;
            temp = numberArray[i];

            for( int j = 0; j < distinctArrayNumbers.length; j++){
                if( numberArray[i] == distinctArrayNumbers[j] ){
                isDistinct = false;
            }


           }
            if(isDistinct){
                    distinctArrayNumbers[temp]=numberArray[i];
                    temp++;
                }


    }
    displayDistinctArray(distinctArrayNumbers);
}

public static void displayDistinctArray(int[] distinctArrayNumbers) {
    for( int i = 0; i < distinctArrayNumbers.length; i++){
        if(distinctArrayNumbers[i] != 0){
        System.out.println(distinctArrayNumbers[i]);
        }
    }
}

}

}