簡體   English   中英

替換為ArrayList

[英]Replacing with ArrayList

如何刪除重復的數字並要求用戶添加新的數字來替換重復的數字? 假設用戶使用我編寫的代碼要求輸入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
        }
    }
}

順便說一句,對不起,對您沒有任何意義。 我很難解釋我的意思。 但是我試圖詳細解釋我需要的一切。

而不是執行s.add(d)並檢查是否為false ,然后嘗試替換重復的數字,而應使用s.contains(d)檢查重復的s.contains(d) 這不會將號碼添加到列表中,並且當用戶提供另一個非重復的號碼時,您可以將其添加到列表中。

我猜你需要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]);
       }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM