如何在java中从带有数组的csv文件中删除记录

r8xiu3jd  于 2021-06-27  发布在  Java
关注(0)|答案(0)|浏览(268)

我只想知道,当你为了删除某个元素而覆盖元素时,你会改变它之后所有元素的位置。问题是当你改变位置时,最后一个元素中的最后一个元素将与最后一个元素中的第二个元素相同。在这段代码中,我将最后一个元素改为空,这是我不想要的。我只想删除它,这样我就可以保存在csv。如果我写空然后它保存'空'在csv作为一个记录,我不想要!请帮帮我!

public static void deleteEntry() {
        int flag = -1;
        Boolean found = false;
        System.out.println("Please provide the name of the contact to delete its entry: ");
        String searchName2 = sc.next().toUpperCase();
        System.out.println(counter);
        try {
            for (int i = 0; i < counter; i++) {
                if (names[i].compareTo(searchName2) == 0) {
                    flag = i;
                    found = true;

                }
            }
        } catch (Exception e) {
        }
        if (flag == -1) {
            System.out.println("Contact Name  NOT Found");
        } else { //record was found, flag is a positive index position
            //if the record is the last record, simply remove it and decrement the counter
            if (flag == counter - 1) {
                System.out.println("Contact Deleted!");
                names[flag] = null;
                numbers[flag] = null;
                counter--;
            }else {

                //record is not the last record, shift all later records down
                for (int i = flag; i < counter-1; i++){
                    names[i] = names[i + 1];
                    numbers[i] = numbers[i + 1];

                }
                System.out.println(counter);
                System.out.println("Contact Deleted!");
                if (names[counter-1].equals(names[counter-2])) {
                    names[counter-1] = "";
                    numbers[counter-1] = "";

                }
        }
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题