【问题标题】:Replacing with ArrayList替换为 ArrayList
【发布时间】:2016-05-17 03:56:00
【问题描述】:

如何删除重复号码并要求用户添加新号码以替换重复号码?假设用户使用我制作的代码要求5 数字:6, 7, 8, 7, 9,输出为Number 7 was duplicated in position 3

现在我需要帮助的是,要求用户添加一个新数字来替换那个 7,这样就不会再有重复了。

所以我希望整个输出为Your numbers without duplicates:,它会打印输入的数字而不会出现任何重复。

它们的输入顺序对我来说很重要,因为我想继续测试 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,"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
        }
    }
}

顺便说一句,如果这对您没有任何意义,我很抱歉。我很难解释我的意思。但我试着详细解释我需要的一切。

【问题讨论】:

标签: java arraylist joptionpane hashset


【解决方案1】:

您应该使用s.contains(d) 检查重复项,而不是执行s.add(d) 并检查false,然后尝试替换重复的号码。这不会将号码添加到列表中,当用户提供另一个不重复的号码时,您可以将其添加到列表中。

【讨论】:

    【解决方案2】:

    我猜你需要 ArrayList.set() 方法。

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

    【讨论】:

      猜你喜欢
      • 2015-02-12
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多