【发布时间】:2023-03-20 19:45:01
【问题描述】:
我尝试仅使用循环和扫描器从用户输入的数组中删除重复项。当我输入 array = {1 , 2 , 1}; 时,我正在尝试不使用任何库方法程序打印 1 3 次。
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] + " ");
}
}
谢谢你,
【问题讨论】:
-
您是否先在 Google 上搜索您的问题标题? stackoverflow.com/questions/10056729/…
-
当您输入问题标题时,它会为您提供具有相似关键字的问题列表。在发布之前检查这些内容。
-
但答案使用 set ...。我希望程序在不使用 set @djechlin 的情况下打印答案
-
在不使用 set @AnubianNoob 的情况下,我找不到删除重复项
-
@user3435095 然后在您的问题中包括您不想拥有库方法。 Stack Overflow 经常受到专业程序员的欢迎,他们认为使用库方法更智能、更有效。您应该明确说明您要手动执行此操作。