use8210 use8210 - 6 months ago 9
Java Question

Replacing with ArrayList

How do I remove duplicated numbers and ask the user to add new numbers to replace the duplicated ones? Let's say the user asks for

5
numbers:
6, 7, 8, 7, 9
using the code I made, the output is
Number 7 was duplicated in position 3


Now what I need help with, is asking the user to add a new number to replace that 7 so there wouldn't be anymore duplicates.

So I want the entire output to be
Your numbers without duplicates:
and it would print the numbers that were input without any duplications.

The order in which they are entered are important to me because I want to keep testing out ArrayList and try not to confuse myself.
This is my code:

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,"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
}
}
}


By the way, I'm sorry if it doesn't make any sense to you. I have a very hard time explaining what I mean. But I tried explaining everything I needed with detail.

AJ. AJ.
Answer

I guess you need ArrayList.set() method.

   for (Integer d : al){
                while (s.add(d) == false){ //replace if with while to keep looking for duplicate
                    JOptionPane.showMessageDialog(null,"Number " + d + " was duplicated in position " + al.lastIndexOf(d));
                    JOptionPane.showMessageDialog(null,"Replace new number"); 


//      al.set(d,[set the new value here]);
       }
  }