Question

I'm new to java and I have a problem with deleting specific data based on the student id from user input. I can only delete the student id but not all the info about that student.

Here is my code:

File inputFile = new File("test.txt");
File tempfile = new File("temp.txt");
Scanner scanner = new Scanner("test.txt");
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
PrintWriter wr = new PrintWriter("temp.txt");
String s = null;
String infoToRemove = JOptionPane.showInputDialog(null, "Enter ID to cancel");

while ((s = br.readLine()) != null) {
    for (int i = 0; i < s.length(); i++) {
        if (s.indexOf(infoToRemove) != -1) {
            s = s.replaceAll(infoToRemove, "");
        }
    }
    wr.println(s);
}

wr.close();
br.close();
inputFile.delete();
tempfile.renameTo(inputFile);

Expected Output:

Before:

jason,100,20,Male,Block 1,Ground Floor

jack,200,20,Male,Block 1,Ground Floor

After user insert ID=100 to delete:

jack,200,20,Male,Block 1,Ground Floor
Was it helpful?

Solution

what you are doing is a bit wrong. you read every line in br("test.txt") and then go through it's characters and checking the same thing over and over searching for some unknown input and removing it

what you want to do is every loop write the current line to the file

something like:

while ((s = br.readLine()) != null) {

    if (s.indexOf(infoToRemove) == -1) {
       wr.println(s);
    }
}

but that's not the best way.

what you want to do is when you create the file that it won't be a meaningless line like:

jason,100,20,Male,Block 1,Ground Floor

jack,200,20,Male,Block 1,Ground Floor

you want, at least for the id to it to be clear. something like

jason,id=100,20,Male,Block 1,Ground Floor

jack,id=200,20,Male,Block 1,Ground Floor

so when you search for it you'll be able to do:

while ((s = br.readLine()) != null) {

    if (s.indexOf("id=" +infoToRemove) == -1) {
       wr.println(s);
    }
}

and it will be exact and won't delete accidentally lines that has other id

OTHER TIPS

Instead of :

        while((s = br.readLine()) != null){ 
            for (int i = 0; i < s.length(); i++) {
                if (s.indexOf(infoToRemove) != -1) {
                    s = s.replaceAll(infoToRemove,"");

                }
            }
                wr.println(s);
        }

write :

        while((s = br.readLine()) != null){ 
             if (s.split(",")[1].containts(infoToRemove)) {
                continue;
             }
             wr.println(s);
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top