Here's what I have so far.

I have one class Directory.java and another class DirectoryWithObjectDesign.java

I need help editing my code that when executed, it will be prompted by 3 commands. Find, Delete, and Add. If asked to find, the user will input find then("stringhere"), then the program will search the .txt file to see if the name is in the file. The Add command will add the name a user inputs to the .txt file if it is not in the .txt file, and finally the delete command will delete a string in the .txt file, if it is in there. I need help adding this to my code.

Directory.Java

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

public class Directory {
    //String array directory for holding directory items
    final int maxDirectorySize = 1024;
    String directory[] = new String[maxDirectorySize];
    int directorySize = 0;
    File directoryFile = null;
    Scanner directoryDataIn = null;
    Directory() {
        directoryFile = new File("directory.txt");
        try {
            directoryDataIn = new Scanner("directory.txt");
        }
        catch (FileNotFoundException e) {
            System.out.printf("File %s not found, exiting!",
                    directoryFile);
            System.exit(0);
            //set up directoryFile to read from directoryFileName for reading
            //Load data from the file into the array directory
        }
        // Loading Directory
        while (directoryDataIn.hasNext())
            directory[directorySize++] = directoryDataIn.nextLine();
    }
        public boolean inDirectory(/*String name*/) {
            //(fill in)
            //returns true if name is in directory and false otherwise
        }
        public boolean add(/*String name*/) {
            //(fill in)
            // add to directory if directory is not full
            // directory size is increased by 1
            // returns true if successful; false o.w
        }
        //returns true if successful in adding name to directory; false otherwise

    public boolean delete(//enter string name here//); {
        //(fill in)
        // if name is in directory, remove it and shift
        // other entries to use freed space; directory size
        // is reduced by 1
        // returns true if successful; false o.w
        //returns true if successful in deleting name; false otherwise
    }
    public void closeDirectory() {
        directoryDataIn.close();
        // close explicitly before writing
        PrintStream directoryDataOut = null;
        // now open the directory data file for writing
        try {
            directoryDataOut = new PrintStream(directoryFile);
        }
        catch (FileNotFoundException e) {
            System.out.println("File %s not found, exiting!");
            System.exit(0);
        }
        // write updated directory back to file
        for (int i = 0; i < directorySize; i++)
            directoryDataOut.println(directory[i]);
        directoryDataOut.close();
    }
}
//sets up the directoryFile for writing (after closing it)
//write updated data to the directoryFile and close it

DirectoryWithObjectDesign.Java

public class DirectoryWithObjectDesign {
    public static void main(String[] args) {
        String directoryDataFile = "directory.txt";
        Directory d = new Directory();
        //Create/initialize the directory object
        //Tell the user the system is ready and waiting to execute commands
        while (stdin.hasNext()) {
            String command = stdin.next().trim();
            // using trim to get rid of leading whitespace
            String name = stdin.nextLine().trim();
            // using trim to get rid of leading + trailing whitespace
            if (command.equalsIgnoreCase("find")) {
                if (d.inDirectory(name))
                    System.out.println(name + " is in the directory");
                else
                    System.out.println(name + " is NOT in the directory");
            } else if (command.equalsIgnoreCase("add")) {
                if (d.add(name))
                    System.out.println(name + " added");
                else
                    System.out.println(name + " already in directory");
            } else if (command.equalsIgnoreCase("delete")) {
                if (d.delete(name))
                    System.out.println(name + " deleted");
                else
                    System.out.println(name + " NOT in directory");
            } else {
                System.out.println("bad command, try again");
            }
            //read the command
            //execute the user command by calling the appropriate method of the
            //directory object and giving the user appropriate feedback
        }
        //close the directory
    }
}

Here's the data in my directory.txt file:
Joan
Mike
Jim
Serena
Barry
Cristian
Vincent
Chengjun
Sunil

Recommended Answers

All 11 Replies

Use String.replaceAll() method to delete/replace strings:
Here's a quick example to delete a string from a file:

import java.io.*;
import java.util.*;
public class Iofile {   
    public static void main(String [] arg)throws Exception{
        System.out.println("Input file: ");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String input=in.readLine();
        System.out.println("String to delete: ");
        String del=in.readLine();
        File SourceFile = new File(input);
        Scanner inputs= new Scanner(SourceFile);
        PrintWriter outputs = new PrintWriter("o"+SourceFile);
        while(inputs.hasNext()){
            String s1 = inputs.nextLine();
            String s2 = s1.replaceAll(del, "");
            outputs.println(s2);
        }
        inputs.close();
        outputs.close();
        System.out.println("Output: o"+input);
    } 
}

You can easily modify the part with s1.replaceAll(del, ""); and insert as a 2nd parameter another string to just replace that string from the file.
Look up the String class.

I don't think this is your code. It is the code template from your assignment. Why? Because each method you are asking for help has comment which is the instruction of what to do! Please show us what you really did inside the methods before asking. If you don't understand what it should be doing, please rephrase your question because the word "helping" is too broad.

PS: @Lucaci, your replaceAll() will create a bug in the program. Below is an example of using replaceAll() with the same pattern string but will affect different string. A person name could be substring of other people's name. Using replaceAll() could unintentionally remove the string.

//For example
String a = "Sam";
String b = "Samuel";
a.replaceAll("Sam", "");   // ==> result in ""
b.replaceAll("Sam", "");   // ==> result in "uel"

PSS: The requirement is to read data from a file and save everything in the memory. The add()/delete() will deal with the file at the end of the method. The find() method deals with memory only!

Taywin, it is my code, I've just worked with the outline that was given to US. I have added several things in the code, I'm just stuck finding the remainder of what is left to do. I read the rules when I signed up, I made sure I did everything I could before asking for help :)

Basically when I run the program, I want it to start, and then the user can give input, based on 3 things. Find, Add, Delete. if I type Find "Jim", it prompts the program to search the .txt file. If "Jim" is in the file, it will return "Yes, Jim is in the file!" if not, "Name doesn't exist," now if the name doesn't exist, I want to be able to go back, and type in Add "Buster", and now the program will write to my .txt file, and now the name "Buster" will be in the .txt file. This is what I'm having trouble adding in, for some odd reason.

OK, that's much clearer question. Thanks for the clarification. Now, I'm going to dig into your code.

You have problem building your data structure in your constructor. You need to correctly build it before you could use it.

Line 16 in Directory class, the Scanner class should be given a File object instead of a file name. You have already created a File object in line 14, use that instead.

Line 3 in DirectoryWithObjectDesign class, you do not need this directoryDataFile variable because your Directory class has the file hard-coded inside the constructor. If it is a requirement, you would have to modify/add the Directory class constructor.

Line 7, where did you initilise stdin variable in this class? If you are using a Scanner, you must initilise a new instance inside this main().

Line 7, you can not use conditionstdin.hasNext() to test the loop because a user may not enter anything via the console yet. You may create a new variable called choice. Then check if it is equal to "find"/"add"/"delete". Also, inside the loop, you need to ask a user again whether the user wants to continue. You should use do-while instead of while because a user needs to go through the program at least once.

Scanner stdin;
try {
  ...  // create new Scanner from System.in
}
catch (...) {
  ...  // catch exception and may need to exit from the program
}
String choice="";
do {
  String name = stdin.nextLine().trim();
  // do your if-else if-else statments
  ...
  ...
} while (choice.equalsIgnoreCase("find") || choice.equalsIgnoreCase("add") || choice.equalsIgnoreCase("delete");

Next will be how to do find(), inDirectory(), add(), and delete()...

When you do find(), you will have to go through the whole array up to the directory size inclusive (is equal to n-1). Compare each value of the data to the incoming string. If it is equal, return the index of where you found it. Once you go through the whole array (up to the directory size) and still could not find it, return a negative value (or anything that will not be in the valid range of the index) at the end of the method.

When you do inDirectory(), you will simply call find() and check whether the value of returned index is inside the valid range. In your case, the valid range is between 0 up to 1024 inclusive (0~1023). If the returned value is in the valid range, return true; otherwise, return false.

When you do add(), you must check whether the directory size is full. If you don't, you could get ArrayOutOfBoundException when the size is larger than the array you have created. You also need to use either inDirectory() to search whether the name exists in your data (you don't need to know where exactly the data exists). If it exists, return false right away. Otherwise, your add would be the same as when you create your data in your constructor. The different is that you will have to write to file after you are done with adding the data into the array. Don't forget to increase the value of directory size.

There are many ways to deal with read/write file in Java. In this case, appending the data to the file is much faster. An example for appending data to the file is here. Remember, the output to append the file is the name entered. Then return true after you are done.

When you do delete(), it is similar to add() at the beginning -- use find() to see if the data exists (you need to obtain the index of where the data exists). If the data does not exist (index is out of valid range), return false right away. Otherwise, you need to do some more work here...

1)You must rearrange/shift all the value from the index+1 to index. You need to use a loop to accomplish this.
2)Decreased the value of directory size by 1.
3)Write all data to file and NOT append the data but overwrite the whole data (easier to write the whole file as new). An example for overwrite the whole file can be seen here.
4)Once everything is done, return true.

Great Taywin, appreciate the information and guidance, will get working on it ASAP, and let you know what I run into from there, cheers !

I've started to set something like this up, however, what can I code in in order for the input to ask me what name I want the directory.txt to search for, and then when entered, it will go and search for the name I entered in the .txt file, and it will let me know if it is in there or not

import java.util.*; //Import to allow you to get user input

public class example
{
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in); //Creates scanner object
        String usrInput;

        System.out.println("Would you like to Find, Add, or Delete?");
        System.out.println("(1) Find");
        System.out.println("(2) Add");
        System.out.println("(3) Delete");
        int choice = in.nextInt(); //Get user input on 
        if (choice != 1 && choice != 2 && choice != 3)
        {
            System.out.println("That was not one of the choices."); //handle if they don't enter a valid choice.
        }
        else if (choice == 1) 
        {
            String Find;
            System.out.println("Please enter the name you wish to search for");
            String searchText = ""; 
            String fileName = "directory.txt"; 
        }}

Before that, you need to create an instance of Directory at the beginning.

Directory dir = new Directory();

Then to answer your question, you could simply do something similar to below because you already have a Scanner initilised.

String searchText = in.nextLine();

Then you would have already accepted the user input for a string name. Then you could do...

if (dir.inDirectory(searchText)) {  // or dir.find(searchText)>=0
  System.out.println("Found the name "+searchText+" in the directory);
}
else {
  System.out.println("Not found "+searchText);
}

Please read more about Scanner class.

Taywin, if you could do me some huge justice, may you please add the code you just showed me into my already previous code? I'm just confusing myself at this point, trying to put it in the right spot. overtired

Ok, please see below...

import java.util.*; //Import to allow you to get user input

public class example {
  public static void main(String[] args) {
    Directory dir = new Directory();  // this should automatically read from file
    Scanner in = new Scanner(System.in); //Creates scanner object
    //String usrInput;  // no need, remove it

    System.out.println("Would you like to Find, Add, or Delete?");
    System.out.println("(1) Find");
    System.out.println("(2) Add");
    System.out.println("(3) Delete");
    int choice = in.nextInt(); //Get user input on 
    // if you check for invalid first, it could be confusing in the future when you deal
    // with multiple invalid. This should guide you the habit to check for valid first.
    if (choice == 1) {
      //String Find;  // no need, remove it
      System.out.print("Please enter the name you wish to search for: ");
      String searchText = in.nextLine();   // accept whole string line from user
      if (dir.inDirectory(searchText)) {
        // display message found
      }
      else {
        // display message not found
      }
    }
    else if (...) {
    }
    ...
    else { //handle if they don't enter a valid choice. (not 1, 2, or 3)
      System.out.println("That was not one of the choices.");
    }
  }
  ...
}

PS: The current code does not keep looping and ask user to find/add/delete again. You need another do-while-loop to wrap around it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.