创建一个ArrayList,然后搜索列表,并允许用户更改列表的一部分

时间:2013-05-21 20:52:53

标签: java arraylist

我们的任务是使用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

如果用户搜索未找到的项目,则会告诉他们“项目”未找到!

1 个答案:

答案 0 :(得分:0)

我将使用indexOf()查找索引,然后如果项目存在(index != -1),您将获得一个索引,然后您可以使用set(int index, E item)替换该项目

例如,您可以执行类似..

的操作
boolean search=true;
while(search) {
  System.out.print("Search..");
  String searchFor = keyboard.nextLine();
  int ind = searchList.indexOf(searchFor);
  if (ind == -1) {
    System.out.println("Not Found");
  } else {
    System.out.print("Replace with.. ");
    String replaceWith = keyboard.nextLine();
    searchList.set(ind, replaceWith);
  }
  System.out.print("Continue searching.. ");
  String ans = keyboard.nextLine( );
  if (!ans.equalsIgnoreCase("yes"))
    search = false;
}