簡體   English   中英

算法 arraylist 刪除重復的字符串並保存到新的文本文件

[英]algorithm arraylist remove String duplicates and save to new text file

我目前正在編寫一種算法,該算法從 a.txt 文件創建 ArrayList,使用循環檢查重復項(其中循環應如下所示:第一行寫入 new.txt & boolean found 設置為 true,因為字符串已經找到了。第 2 行被寫入 new.txt 等。但是如果兩個字符串相同,則重復的,即第二個字符串應該被忽略並繼續下一個)。

public class test {

public static void main(String[] args) throws IOException {
    String suche = "88 BETRAG-MINUS VALUE 'M'.";
    String suche2 = "88 BETRAG-PLUS VALUE 'P'";
    boolean gefunden = false;
    File neueDatei = new File("C:\\Dev\\xx.txt");
    if (neueDatei.createNewFile()) {
        System.out.println("Datei wurde erstellt");
    }

    if (gefunden == false) {
        dateiEinlesen(null, gefunden);
        ArrayList<String> arr = null;
        inNeueDateischreiben(neueDatei, gefunden, arr, suche, suche2);

    }
}

public static void dateiEinlesen(File neueDatei, boolean gefunden) {

    BufferedReader reader;
    String zeile = null;

    try {
        reader = new BufferedReader(new FileReader("C:\\Dev\\Test.txt"));
        zeile = reader.readLine();

        ArrayList<String[]> arr = new ArrayList<String[]>();

        while (zeile != null) {
            arr.add(zeile.split(" "));
            zeile = reader.readLine();
        }
        System.out.println(arr);

    } catch (IOException e) {
        System.err.println("Error2 :" + e);
    }

}

public static void inNeueDateischreiben(File neueDatei, boolean gefunden, ArrayList<String> arr, String suche2,
        String suche22) throws IOException {
    FileWriter writer = new FileWriter(suche22);
    String lastValue = null;
    for (Iterator<String> i = arr.iterator(); i.hasNext();) {
        String currentValue = i.next();
        if (lastValue != null && currentValue.equals(lastValue)) {
            i.remove();
            {
                writer.write(suche2.toString());
                gefunden = true;

            }

        }
        writer.close();
    }

}

}

您的變量命名(suche2、suche22)使閱讀代碼變得困難。

除此之外,你的寫作算法看起來很有趣。 您只比較相鄰的行,而重復的行可能在任何地方。 此外, writer.write僅在您找到重復項時才會命中。 還有你怎么稱呼它和其他東西看起來不正確。

以下是正確編寫此內容的一些一般步驟:

  1. 打開文件,以便您可以逐行閱讀。
  2. 創建文件寫入器
  3. 創建一個集合或字典之類的數據結構,使您能夠在恆定時間內查找項目。
  4. 對於您閱讀的每一行,請執行以下操作:
  • 查看字典中是否存在該行。
  • 如果沒有,將其寫入新文件
  • 如果它已經存在於字典中,請跳到第 4 步。
  • 將該行添加到字典中以供以后比較,並將 go 添加到步驟 4。
  1. 當行用完時關閉兩個文件。

我建議,你完全重寫你的代碼,因為當前版本很難修改。

暫無
暫無

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

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