我在java中创建任务列表,并希望能够按用户输入的截止日期对数据进行排序。以下是我到目前为止的情况。对于switch语句的case 3,我想在情况2中按变量dueDate排序:我怎么能访问它?我可以使用collection.sort作为日期吗?
import java.io.*;
import java.util.Scanner;
public class Main {
public static String fileName = "/Users/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();
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();
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 + " " + dueDate);
outFile.close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
static void sortList(){
System.out.println("\nSorted List\n");
}
}
答案 0 :(得分:0)
是的,您可以使用Collections.sort()。
但是,您需要实现Comparable或Comparator来添加您自己的逻辑以对其进行排序。
尝试搜索可比较和比较器,你应该看看如何做。