0

I am unsure on how to give the user an option to add / delete a name from the existing text file. The current code works fine and reads in names from the text file. Could someone give me a hand on this?

import java.io.File;
import java.util.Scanner;


public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {

  String[] names = new String[100];
  Scanner scan = new Scanner(new File("names.txt"));
  int index = 0;

  while (scan.hasNext()){
    names[index]=(scan.nextLine());
    index++;
  }

  for(int i = 0; i < index; i++){
    System.out.println(names[i]);
  }

    scan.close();
}


}
Shadow
  • 3,926
  • 5
  • 20
  • 41
the_no_1
  • 25
  • 1
  • 8
  • 1
    Eclipse has nothing to do with this. – Maroun Dec 09 '14 at 11:42
  • You're on the right track. It's kind of tricky to edit files in place with java. Perhaps the easiest way would be to read and store the entire lines (what you already do), and then use a `Printer` to write the altered data back into the same file. – Zoltán Dec 09 '14 at 11:44
  • google how to write string to file, then you have both writing and reading. Then you can figure out the rest of the logic easily :) – Bart Hofma Dec 09 '14 at 11:44

1 Answers1

1

It is possible, almost everything is, but you'll find it very difficult to do using arrays.

I would instead use an ArrayList which is similar, but much, much better than just regular ol' arrays.

A String ArrayList is defined like so:

ArrayList<String> names = new ArrayList<String>();

You can add using the add function of the ArrayList:

while (scan.hasNext())
    names.add(scan.nextLine());

Then, to remove a name from the text file, just remove it from the names ArrayList using the remove function, and write the modified ArrayList to the file:

names.remove("Some Name Here");
PrintWriter writer = new PrintWriter("names.txt", "UTF-8");
for (int i = 0; i < names.size(); i++)
    writer.println(names.get(i));
writer.close();

Likewise, to add a new name to the file, just add the new name to the ArrayList before you write it to the file, using the add function

Shadow
  • 3,926
  • 5
  • 20
  • 41
  • But this requires reading the entire file just to delete one name. Is that what OP wants? If not, then `RandomAccessFile` might be a better (and perhaps only?) way to go. – Chthonic Project Dec 09 '14 at 11:55
  • This is good thanks. But I need a loop so that the computer asks the user whether they want to add or delete names until they are done. Thanks – the_no_1 Dec 09 '14 at 12:09