电话簿程序在Java中不起作用

时间:2014-12-17 18:49:26

标签: java

我正在创建一个类似电话簿的程序。我将我的联系人写在一个文本文件中。我的程序应该读取文本文件中的联系人,还允许用户添加联系人并删除联系人。通过这样做,它还应该更新文本文件。 所以这是我的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ContactListDriver
{
public static void main(String [] args) throws IOException, FileNotFoundException
{
    File inputFile = new File("C:/Users/Gab Real/workspace/CSc121/MyContacts.txt");
    //System.out.println(String.format("File.canWrite() says %s", inputFile.canWrite()));

    //System.out.println(inputFile.getAbsolutePath());  
    BufferedReader reader = null;
    BufferedReader reader2 = null;
    BufferedReader reader3 = null;
    PrintWriter out = null;
    File tempFile = new File("temp1.txt");
    try{
    reader = new BufferedReader(new FileReader(inputFile));
    out = new PrintWriter(tempFile);
    Scanner scan = new Scanner(System.in);
    String word = "";

    System.out.println("oooooooooooooooooooooo[Instructions]ooooooooooooooooooooooooooooooooooo");
    System.out.println("o use command 'add' to add a contact (e.g. add Gabrielle 2548-5878-555) o");
    System.out.println("o use command 'remove' + the name of the contact to remove a Contact  o");
    System.out.println("o use command 'exit' to exit the program                              o");
    System.out.println("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo");

    while(!word.contentEquals("exit")){
    System.out.println("\nEnter a command: ");
    word = scan.nextLine();
    String entries[] = word.split(" ");


    if(word.startsWith("add")){
        out.append(entries[1] + " " + entries[2]);
        //out.println(out.toString());
        //out.write("\r\n");
    } else if (word.contains("remove")){
        String currentLine;
        while((currentLine = reader.readLine()) != null) {
            // trim newline when comparing with lineToRemove
            String trimmedLine = currentLine.trim();
            if(trimmedLine.contains(entries[1])) continue;
            out.println(currentLine);
        }
    } else if (word.contains("show")){
        String currentLine;
        while((currentLine = reader.readLine()) != null) {
            // trim newline when comparing with lineToRemove
            System.out.println(currentLine); 
        }
    }
}


    }
    finally {
        out.close();
        reader.close();
        }

  }
}

我遇到的问题如下:

  1. 有些时候,当我添加联系人时,文本文件在退出程序后变空。

  2. 我只能显示/删除一次联系人。它不允许我多次显示联系人或删除多个联系人。

1 个答案:

答案 0 :(得分:0)

这应该解决你的问题..

我对代码进行了一些更改,因此很难解释所有内容,但我已经在代码之后包含了主要内容。如果有任何疑问,请尝试浏览并添加评论。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ContactListDriver {

    public static void main(String[] args) throws IOException, FileNotFoundException {
        File inputFile = new File("C:/Users/Gab Real/workspace/CSc121/MyContacts.txt");
        //System.out.println(String.format("File.canWrite() says %s", inputFile.canWrite()));

        //System.out.println(inputFile.getAbsolutePath());  
        BufferedReader reader = null;
        BufferedReader reader2 = null;
        BufferedReader reader3 = null;
        FileWriter out = null;
        String ls = System.getProperty("line.separator");
        //File tempFile = new File("temp1.txt");
        try {
            Scanner scan = new Scanner(System.in);
            String word = "";

            System.out.println("oooooooooooooooooooooo[Instructions]ooooooooooooooooooooooooooooooooooo");
            System.out.println("o use command 'show' to show all contacts                             o");
            System.out.println("o use command 'add' to add a contact (e.g. add Gabrielle 25485878555) o");
            System.out.println("o use command 'remove' + the name of the contact to remove a Contact  o");
            System.out.println("o use command 'exit' to exit the program                              o");
            System.out.println("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo");

            while (!word.contentEquals("exit")) {
                System.out.println("\nEnter a command: ");
                word = scan.nextLine();
                String entries[] = word.split(" ");

                if (entries[0].equalsIgnoreCase("add")) {
                    out = new FileWriter(inputFile, true);
                    out.write(ls + entries[1] + " " + entries[2]);
                    out.flush();
                    //out.println(out.toString());
                    //out.write("\r\n");
                } else if (entries[0].equalsIgnoreCase("remove")) {
                    String allLines = "";
                    String currentLine;
                    reader = new BufferedReader(new FileReader(inputFile));

                    while ((currentLine = reader.readLine()) != null) {
                        allLines = allLines + "|" + currentLine;
                    }
                    String[] allLinesArr = allLines.split("\\|");

                    out = new FileWriter(inputFile, false);
                    for (int i = 0; i < allLinesArr.length; i++) {
                        currentLine = allLinesArr[i];
                        if (currentLine.contains(entries[1])) {
                            System.out.println("Deleting " + entries[1]);
                            continue;
                        }
                        if (i == 0) {
                            out.write(currentLine);
                        } else {
                            out.write(ls + currentLine);
                        }
                    }
                    out.flush();
                } else if (entries[0].equalsIgnoreCase("show")) {
                    reader = new BufferedReader(new FileReader(inputFile));
                    String currentLine;
                    while ((currentLine = reader.readLine()) != null) {
                        // trim newline when comparing with lineToRemove
                        System.out.println(currentLine);
                    }
                }
            }

        } finally {
            if (out != null) {
                out.close();
            }
            if (reader != null) {
                reader.close();
            }
        }

    }
}

需要注意的要点:

  • PrintWriter中的第二个参数(true / false)表示是追加(true)还是覆盖(false)
  • BufferedReader在函数内部声明,以便重新启动从文件启动读取(解决多次显示问题)
  • 'remove'中的PrintWriter是中途,因为在声明时,文件将被清空(因此我首先将其内容转换为'|'分隔的字符串)

只剩下多个删除部分。这样做的逻辑是允许用户输入多个以“”分隔的名称(因此填充你的条目数组)&amp;在删除位内,循环遍历数组长度(从index = 1到index = entries.length)并将if条件放入其中。

注意:我不确定我是否需要在finally块中放入if条件。但保持它更安全。