gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:26:22 24 4
gpt4 key购买 nike

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

我在函数 checkDuplicate 的 else if 行上收到错误。

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

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;
}
}

最佳答案

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

关于java - 打印数组中不同的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/674618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com