【问题标题】:algorithm arraylist remove String duplicates and save to new text filealgorithm arraylist 删除重复的字符串并保存到新的文本文件
【发布时间】:2022-01-20 08:01:05
【问题描述】:

我目前正在编写一个从 .txt 文件创建 ArrayList 的算法,并使用循环检查它是否存在重复项(其中循环应如下所示: 第一行写入新的 .txt & boolean found 设置为 true,因为字符串已经找到。 第 2 行写入新的 .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();
    }

}

}

【问题讨论】:

  • 你的问题是什么?
  • 我知道我的代码错了,但我不知道哪里错了。
  • dateiEinlesen() 应该返回 ArrayList,然后将其传递给 inNeueDateischreiben() 方法。目前,您不返回/传递信息。您目前仅在您的dateiEinlesen() 中打印arr
  • 你现在很可能得到NullPointerException,因为你将null传递给inNeueDateiSchreiben()。但是关于正在发生的事情的信息是应该提供的,而不是指望人们弄清楚。
  • 你怎么知道是错的?你收到错误信息了吗?有没有意外的输出?我现在已经问了你四个问题,而你还没有只问一个...:/

标签: java algorithm duplicates


【解决方案1】:

您的变量命名(suche2、suche22)使阅读代码变得困难。

除此之外,你的写作算法看起来很有趣。您只比较相邻的行,而重复的行可能在任何地方。此外,writer.write 仅在您找到重复项时才会出现。还有你怎么称呼它和其他东西看起来不正确。

以下是正确编写此代码的一些一般步骤:

  1. 打开文件,以便您可以逐行阅读。
  2. 创建文件写入器
  3. 创建一个类似于集合或字典的数据结构,使您能够在恒定时间内查找项目。
  4. 对于您阅读的每一行,请执行以下操作:
  • 查看字典中是否存在该行。
  • 如果没有,将其写入新文件
  • 如果字典中已经存在,请跳到第 4 步。
  • 将该行添加到字典中以供以后比较,然后转到第 4 步。
  1. 当行数用完时关闭两个文件。

我建议,你完全重写你的代码,因为当前版本很难修改。

【讨论】:

    猜你喜欢
    • 2019-12-10
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2018-07-19
    相关资源
    最近更新 更多