首页 > 解决方案 > 如何在 ArrayList 中搜索元素?- 爪哇

问题描述

我在 Java 中创建了一个待办事项列表程序,您可以在其中添加、删除和查看具有特定名称、日期、时间等的任务。

但是,我正在尝试添加一个选项,当用户选择“5”时,他们可以输入日期,如果有任何任务落在该特定日期,它们将被列出。

例如:

----------------------
Main Menu
----------------------
1. Add a task
2. Delete a task
3. Delete all tasks
4. List all tasks
5. Search for a task
6. Exit the program

Enter choice: 5

Enter a date: 20/10/2020

Here are the tasks for 20/10/2020:

-task1-
-task2-
etc...

到目前为止,当我这样做时,即使在该特定日期确实存在任务,也不会返回任何任务。

到目前为止,这是我的代码:

public void searchTasks() throws ParseException {
System.out.println("Search for a task: ");
System.out.println("----------------------");
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a date (dd/mm/yyyy): ");

Scanner scanner = new Scanner(System.in);
String date = scanner.nextLine();

LocalDate theDate = LocalDate.parse(date, formatter);
String backToStr = formatter.format(theDate);

boolean found = false;
for (String task: currentList){
       String searched_date = task.split(", ")[1];
       if (searched_date.equals(backToStr)){
           found = true;
           System.out.println();
           System.out.println("----------------------");
           System.out.println("Here are the tasks on " + backToStr + ":");
           System.out.println("----------------------");
           System.out.println(task);
       }
}
if (!found){  // if there was no task found for the specified date
    System.out.println("No tasks found on this date");
}

}

标签: javaarraylist

解决方案


当您添加theItemcurrentListusingcurrentList.add(theItem)时,您正在添加项目的所有信息(标题、日期、时间......)。

当您使用 搜索任务contains(date)时,您只搜索日期。因此,幕后发生的事情是将日期(例如,'20/10/2020')与更长的时间(例如,'myTitle,20/10/2020,晚上 10 点......')进行比较,但他们没有匹配,因此不显示任务。


推荐阅读