【发布时间】:2016-05-17 02:01:40
【问题描述】:
如何删除 ArrayList 上的重复数字并将其替换为新数字?
我想打印不重复的数字。
这是我的代码:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
int opt = Integer.parseInt(JOptionPane.showInputDialog("How many numbers?");
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
Set<Integer> s = new HashSet<>();
for (Integer d : al){
if (s.add(d) == false)
JOptionPane.showMessageDialog(null,"The number " + d + " was duplicated in position " + al.lastIndexOf(d));
JOptionPane.showMessageDialog(null,"Replace new number"); //This is where I would like to replace the numbers if possible
}
JOptionPane.showMessageDialog("Your numbers without duplicates: "); //This is where it would print
}
}
}
【问题讨论】:
-
您似乎已经进行了一些编码。现在有什么问题?什么不工作?你的期望是什么,你目前的输出是什么?
-
换成什么?
-
假设我想要 4 个数字。
3,4,3,2我想替换第二个3所以它应该说Replace new number我添加一个7 -
如果换成4呢?
-
它会要求我再次替换,因为我不想要重复的数字
标签: java arraylist joptionpane hashset