我们的任务是使用 Arraylist 编码创建一个待办事项列表。
然后更改代码,使其在输入列表后要求用户输入一个字符串,它会告诉用户该字符串是否存在于列表中。
最后,如果已找到该字符串,则允许用户输入另一个字符串并替换原来的字符串。然后打印出列表。
这就是我所拥有的:我不确定如何继续。
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> toDoList = new ArrayList<String>();
System.out.println("Enter items for the list, when prompted.");
boolean done = false;
Scanner keyboard = new Scanner(System.in);
while (!done)
{
System.out.println("Type an entry:");
String entry = keyboard.nextLine( );
toDoList.add(entry);
System.out.print("More items for the list? ");
String ans = keyboard.nextLine( );
if (!ans.equalsIgnoreCase("yes"))
done = true;
}
System.out.println("The list contains:");
int listSize = toDoList.size( );
for (int position = 0; position < listSize; position++)
System.out.println(toDoList.get(position));
)
)
我注意到我可以合并:
ArrayList<String> searchList = new ArrayList<String>();
String search = "a";
int searchListLength = searchList.size();
for (int i = 0; i < searchListLength; i++) {
if (searchList.get(i).contains(search)) {
//Where do I put it after the List is printed or before? Any Help would be appricated
}
}
这是我正在尝试做的示例输出:
Enter items for the list, when prompted.
Type an entry:
Alice
More items for the list? yes
Type an entry:
Bob
More items for the list? yes
Type an entry:
Carol
More items for the list? no
The list contains:
Alice
Bob
Carol
Enter a String to search for:
Bob
Enter a String to replace with:
Bill
Bob found!
The list contains:
Alice
Bill
Carol
如果用户搜索未找到的项目,那么它会告诉他们“项目”未找到!