java - 如何在 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");
}
}
解决方案
当您添加theItem
到currentList
usingcurrentList.add(theItem)
时,您正在添加项目的所有信息(标题、日期、时间......)。
当您使用 搜索任务contains(date)
时,您只搜索日期。因此,幕后发生的事情是将日期(例如,'20/10/2020')与更长的时间(例如,'myTitle,20/10/2020,晚上 10 点......')进行比较,但他们没有匹配,因此不显示任务。
推荐阅读
- python-3.x - Python异步队列没有完成
- javascript - 按键过滤地图
- angularjs - Angular 混合错误:试图在设置之前获取 AngularJS 注入器
- css - 为什么动画 div 向上移动,然后以跳跃结束?
- xml - Angular 5 http服务响应错误
- lucene.net - 如何在自定义智能搜索 Web 部件中允许前导通配符 (Kentico 10)
- javascript - Vue CLI 3:热重载需要很长时间才能重建
- ibm-cloud-infrastructure - 如何通过 SL API 订购没有公共 NIC 的裸机
- javascript - JavaScript 数组失去作用域并且没有传递到我的函数中
- java - Groovy 匹配以正则表达式结尾