java数组是否删除重复项?

java数组是否删除重复项?,java,arrays,loops,Java,Arrays,Loops,我试图从用户输入的数组中删除重复项,只使用循环和扫描仪。当我输入数组={1,2,1}时,我尝试不使用任何库方法;该程序将1打印三次 import java.util.*; public class Duplicates { public static void main(String []args) { Scanner kb = new Scanner(System.in); // The size System.out.print("Enter the size o

我试图从用户输入的数组中删除重复项,只使用循环和扫描仪。当我输入数组={1,2,1}时,我尝试不使用任何库方法;该程序将1打印三次

import java.util.*;

public class Duplicates {
public static void main(String []args) {
    Scanner kb = new Scanner(System.in);

    // The size
    System.out.print("Enter the size of the array: ");
    int n = kb.nextInt();

    // the elements
    System.out.printf("Enter %d elements in the array: ", n);
    int [] a = new int[n];
    for(int i = 0; i < a.length; i++)
        a[i] = kb.nextInt();

    // remove duplicate elements
    for(int i = 0; i < a.length; i++){
        for(int j = i+1; j < a.length; j++){
            if (a[j] != a[i]){
                a[j] = a[i];
                ++j;
            }
            a[j] = a[i];
        }
    }

    // print
    for(int k = 0; k < a.length; k++)
        System.out.print(a[k] + " ");

}
}
import java.util.*;
公共类副本{
公共静态void main(字符串[]args){
扫描仪kb=新扫描仪(System.in);
//大小
System.out.print(“输入数组的大小:”);
int n=kb.nextInt();
//元素
System.out.printf(“在数组中输入%d个元素:”,n);
int[]a=新的int[n];
for(int i=0;i

谢谢,

如果您使用
lang
库,有一种方法可以从
数组中删除元素

注意:下面的源代码取自此链接

来源:


你先用谷歌搜索你的问题标题了吗?当你输入一个问题标题时,它会给你一个带有相似关键字的问题列表。在发布之前检查这些。但是答案使用set。。。。我希望程序在不使用set的情况下打印答案@djechlinI没有发现在不使用set的情况下删除重复项@AnubianNoob@user3435095然后在你的问题中包括你不想有库方法。堆栈溢出经常被专业程序员使用,他们认为使用库方法更聪明、更有效。你应该特别声明你想手动操作。有没有办法不用ArrayUtils来解决这个问题?
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

public class RemoveObjectFromArray{

    public static void main(String args[]) {

        //let's create an array for demonstration purpose
        int[] test = new int[] { 101, 102, 103, 104, 105};

        System.out.println("Original Array : size : " + test.length );
        System.out.println("Contents : " + Arrays.toString(test));

        //let's remove or delete an element from Array using Apache Commons ArrayUtils
        test = ArrayUtils.remove(test, 2); //removing element at index 2

        //Size of array must be 1 less than original array after deleting an element
        System.out.println("Size of array after removing an element  : " + test.length);
        System.out.println("Content of Array after removing an object : "
                           + Arrays.toString(test));

    } 

}