Address book program with more functionality

那年仲夏 提交于 2019-12-25 01:45:09

问题


I've done a small address book program that allows the user to:

  1. add contact
  2. search contact
  3. delete contact
  4. display all contacts

It ends after you enter one option, I want it to keep running until the user says eg 5- exit

another problem I want the data to written and read to data.dat file

I'm completly new, can some tell me how to split up this into separate classes and inherit each other.

my code:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class AddressBookOperations
{


    public static void main(String[] args) throws IOException
    {
        String s = null;
        String s2 = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Console in = System.console();

        System.out.println(" Please select the required operations.\n"
                        + " 1- Add contact\t 2- search contact\t 3- delete contact\t 4- display all contacts\n");
        s2 = in.readLine();
        if (s2 != null && !(s2.equals("1") || s2.equals("2") || s2.equals("3") || s2.equals("4")))
        {
            System.out.println("Invalid Operation Selected\n");
            System.exit(0);
        }

        else
        {
            s = s2;
        }

        if (s != null)
        {
            String dataLine;
            String data;
            if (s.equals("1")) {
                System.out.println("Name: ");
                dataLine = in.readLine();
                data = dataLine;
                in = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("PhoneNumber: ");
                dataLine = in.readLine();
                data = data + ":" + dataLine;
                writeToFile("C:/AddressBook.bat", data, true, true);
            } else if (s.equals("2")) {
                System.out.println("Enter Name 0r PhoneNumber: ");
                dataLine = in.readLine();
                String result = readFromFile("C:/AddressBook.bat", dataLine);
                System.out.println("Search Results\n" + result);
            } else if (s.equals("3")) {
                System.out.println("Enter Name: ");
                dataLine = in.readLine();
                data = dataLine;
                System.out.println("PhoneNumber: ");
                dataLine = in.readLine();
                data = data + ":" + dataLine;
                deleteFromFile("C:/AddressBook.bat", data);
            } else if (s.equals("4")) {
                String result = readFromFile("C:/AddressBook.bat", null);
                System.out.println("Search Results\n" + result);
            }
        }

    }

    private static void deleteFromFile(String string, String dataLine) {
        String data = readFromFile(string, null);
        data = data.replaceAll(dataLine, "");
        writeToFile(string, data, false, false);
    }

    public static boolean writeToFile(String fileName, String dataLine,
            boolean isAppendMode, boolean isNewLine) {
        if (isNewLine) {
            dataLine = "\n" + dataLine;
        }

        try {
            File outFile = new File(fileName);
            DataOutputStream dos;
            if (isAppendMode) {
                dos = new DataOutputStream(new FileOutputStream(fileName, true));
            } else {
                dos = new DataOutputStream(new FileOutputStream(outFile));
            }

            dos.writeBytes(dataLine);
            dos.close();
        } catch (FileNotFoundException ex) {
            return (false);
        } catch (IOException ex) {
            return (false);
        }
        return (true);

    }

    /*
     * Reads data from a given file
     */
    public static String readFromFile(String fileName, String dataLine2) {
        String DataLine = "";
        String fileData = "";
        try {
            File inFile = new File(fileName);
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(inFile)));
            if (dataLine2 != null)
            {
                while ((DataLine = br.readLine()) != null)
                {
                    if (DataLine.contains(dataLine2)) {
                        fileData = DataLine;
                    }
                }
            }

            else
            {
                while ((DataLine = br.readLine()) != null)
                {
                    fileData = fileData + "\n" + DataLine;
                    //System.out.println(DataLine);
                }
            }
            br.close();
        }

        catch (FileNotFoundException ex)
        {
            return (null);
        } catch (IOException ex)
        {
            return (null);
        }
        return (fileData);

    }

    public static boolean isFileExists(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }
}

回答1:


You can wrap your logic in a while loop which terminates when a given boolean is true, therefore you will keep going back to the start after each operation is performed. For example:

boolean isRunning = true;

while (isRunning) {
  //your code here

  if (s2.equals("5")) {
    isRunning = false;
  }
}

You should also move all of your logic out of main() and into its own seperate function that is called from main(). I'm also not sure why you are writing to a .bat file? Change the extension to .dat if you want to write to a .dat file.




回答2:


I guess you just want a general code review. Here are my thoughts:

1. Scanner is much easier to use for console input because you can specify input types, such as nextInt(). To initialize it, just use

Scanner sc = new Scanner(System.in);

You can use the same Scanner for every user input in the course of the program. Also, remember to call Scanner.close() before your program exits.

2. Initialize your BufferedReader as follows:

// file is a String variable
BufferedReader in = new BufferedReader(new FileReader(file));

Analogously, read files as follows:

BufferedWriter br = new BufferedWriter(new BufferedReader(file));

3. To keep the program running, practice implementing a do-while block:

boolean quit = false;
do {
  // loop program; when user is finished, set quit = true
} while (!quit)

4. For the conditionals based on "Please select the required operations", practice implementing a switch block.

5. Separate the logic for parsing the user input and the logic for operating on the address book by making the console interface a separate class, say, AddressBookUI. When it is runs, it should immediately create an instance of the AddressBookOperations class, and call appropriate methods from there based on user input - AddressBookOperations should have a separate method for each operation (this will also make your switch quite short). It should also have the following private (but not static) variables to store the filename and BufferedRead/Writer. The class should have a constructor with an String filename argument which initializes these variables.

6. Deleting specific lines in files is rather tricky in Java. Try this:

  1. Create a BufferedReader for the file.
  2. Create a new temporary file, and create a BufferedWriter for it.
  3. Read the file line by line. For each line, if it is not the line you want to delete, write it to the temporary file.
  4. Close the reader and the writer
  5. Delete the old file
  6. Rename the temp file to the filename.


来源:https://stackoverflow.com/questions/8467481/address-book-program-with-more-functionality

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!