如何删除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
}
}
}
答案 0 :(得分:0)
防止在用户输入重复的数字时输入重复的数字,而不是在以后检查和替换它们。
在这个地方做:
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
如果一个号码已经存在则chceck,如果是,则要求另一个号码不重复,如果是,则添加它并要求下一个号码:
for (int i=0 ; i < opc ; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while( true ){
if( ! al.contains( myNumber ))
al.add( myNumber );
break;
}
myNumber = Integer.parseInt(JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
}
========编辑==================
我已经纠正了这个例子。在上述(上一个){
之后,if
之后缺少public class MmuClass {
public static void main(String... wwwx) {
List<Integer> lst = Arrays.asList(4, 2, 6, -6, 9);
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while (true) {
if (!al.contains(myNumber)) {
al.add(myNumber);
break;
}
myNumber = Integer.parseInt(
JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
al.stream().forEach(System.out::println);
}
}
}
:
UpdateItemMutation