实现可比较的java

时间:2016-02-07 17:49:56

标签: java compare comparable

我正在尝试使用类似的界面按日期排序用户输入的任务和日期列表。我在外部.txt文件中有任务,如果我访问正确的变量,我有点困惑。程序编译,但当我尝试对任务进行排序时,它似乎擦除了文件的内容。这就是我所拥有的:

public class DueDate implements Comparable<DueDate>{

    public String addedTask = "";
    public String enteredDueDate;


    public DueDate(String addedTask, String dueDate){

        this.addedTask = addedTask;
        this.enteredDueDate = enteredDueDate;
    }

    public String toString(){
        return addedTask+"\t"+enteredDueDate+"\t";
    }

    @Override
    public int compareTo(DueDate o) {
        return this.enteredDueDate.compareTo(o.enteredDueDate);
    }
}

public class Main {

    public static String fileName = "/Users/eringray/Desktop/tasklistjava/src/javatask.txt";

    public static void main(String[] args) throws IOException {

        int menuItem = -1;
        while(menuItem != 0){
            menuItem = menu();
            switch (menuItem){
                case 1:
                    showTaskList();
                    break;
                case 2:
                    addTask();
                    break;
                case 3:
                    sortList();
                case 4:
                    deleteTasks();
                    break;
                case 0:
                    break;
                default:
                    System.out.println("Invalid Input");

            }
        }
    }



    static int menu(){
        int choice;
        Scanner sc = new Scanner(System.in);
        System.out.println("\n Task List Menu \n");
        System.out.println("0: Exit Menu");
        System.out.println("1: Show Tasks in List");
        System.out.println("2: Add Task to List");
        System.out.println("3: Sort Tasks by Due Date");
        System.out.println("4: Delete Tasks");
        System.out.println();
        System.out.println("Enter a choice: ");
            choice = sc.nextInt();
            return choice;
    }

    static void showTaskList(){
        System.out.println("\nTask List\n");
        try {
            Scanner inFile = new Scanner(new FileReader(fileName));
            String line;
            int number = 1;
            while(inFile.hasNextLine()){
                line = inFile.nextLine();
                System.out.println(number + ". " + line);
                ++number;
            }
            System.out.println();
            inFile.close();
        } catch (FileNotFoundException ioe) {
            System.out.println(ioe);
        }
    }

    static void addTask(){
        System.out.println("\nAdd Task\n");
        try {
            Scanner input = new Scanner(System.in);
            PrintWriter outFile = new PrintWriter(new FileWriter(fileName, true));
            System.out.println("Enter a Task: ");
            String addedTask = input.nextLine();
            System.out.println("Set Due Date for this Task(yyyy-mm-dd): ");
            String dueDate = input.nextLine();
            outFile.println(addedTask + "\t" + dueDate);
            outFile.close();
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }
    static void sortList() throws IOException {
        System.out.println("\nSorted List\n");
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
            ArrayList<DueDate> tasks = new ArrayList<DueDate>();
            String line = "";
            while((line = br.readLine()) != null) {
                String[] values = line.split("\t");

                if(values.length == 2) {
                    String addedTask = values[0];
                    String enteredDueDate = values[1];

                    DueDate d = new DueDate(addedTask, enteredDueDate);

                    tasks.add(d);
                }
            }

            Collections.sort(tasks);

            for(int i = 0; i < tasks.size(); i++){
                DueDate date = tasks.get(i);
                String lineText = date.toString();
                bw.write(lineText);
                bw.newLine();
            }

            br.close();
            bw.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
    private static void deleteTasks(){
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        assert writer != null;
        writer.print("");
        writer.close();
        }

    }

对于额外的代码感到抱歉,但认为这可能有助于您了解我尝试做的事情。任何建议都会很棒。我是Java的新手,所以请耐心等待我!谢谢!

1 个答案:

答案 0 :(得分:3)

问题是break中的switch语句丢失,在调用deleteTasks()后调用了sortList()方法。将您的代码更改为此,它应该可以正常工作:

int menuItem = -1;
while(menuItem != 0){
    menuItem = menu();
    switch (menuItem){
        case 1:
            showTaskList();
            break;
        case 2:
            addTask();
            break;
        case 3:
            sortList();
            break; //The missing break
        case 4:
            deleteTasks();
            break;
        case 0:
            break;
        default:
            System.out.println("Invalid Input");
    }
}

DueDate类的构造函数缺少enteredDueDate变量的赋值,因为参数名为dueDate而不是enteredDueDate。你应该把它改成这样的东西:

public DueDate(String addedTask, String enteredDueDate){
    this.addedTask = addedTask;
    this.enteredDueDate = enteredDueDate;
}

因为您当前正在将成员变量分配给它自己的值。 您还应该考虑更改sortList方法,尤其是BufferedWriter,否则每次调用时都会复制列表。这样的事情可以做到:

BufferedReader br = new BufferedReader(new FileReader(fileName));
ArrayList<DueDate> tasks = new ArrayList<DueDate>();
String line = "";
while((line = br.readLine()) != null) {
    String[] values = line.split("\t");
    if(values.length == 2) {
        String addedTask = values[0];
        String enteredDueDate = values[1];
        DueDate d = new DueDate(addedTask, enteredDueDate);
        tasks.add(d);
    }
}
Collections.sort(tasks);
br.close();
//Changed it to not append but overwrite the old file so it only contains the sorted list
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, false));
for (DueDate date : tasks) {
    String lineText = date.toString();
    bw.write(lineText);
    bw.newLine();
}
bw.flush();
bw.close();

编辑:要打印已排序的列表,您可以执行一些操作。 最简单的方法可能是将showTaskList方法的调用附加到sortList方法的末尾,如下所示

    //...
    bw.flush();
    bw.close();
    showTaskList();
} catch (FileNotFoundE
    e.printStackTrace(
}

或者您可以遍历ArrayList并将其打印出来:

    //...
    bw.flush();
    bw.close();
    for (int i = 0; i < tasks.size(); i++) {
        DueDate dueDate = tasks.get(i);
        System.out.println(i+". "+dueDate.toString());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

编辑2 :排序时将所有TasksDueDate放到底部的最简单方法是更改​​{{1}中的compareTo方法class:

DueDate

只是否定它所以所有条目都按降序排序,而那些空@Override public int compareTo(DueDate o) { return -this.enteredDueDate.compareTo(o.enteredDueDate); } 的条目将在列表的末尾(它默认继续比较字符串的方式)。
但是,如果您希望在没有截止日期的情况下使用DueDate,那么您的Tasks方法会遇到问题,因为sortList方法只会返回长度为1且{{1}的数组1}}条件会失败。解决它的一种方法是这样的:

split("\t")

或更紧凑的版本(完全相同)

if

希望这会有所帮助(: