-1

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

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

4

1 回答 1

0

我将使用它indexOf()来查找索引,然后如果 item exists( 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;
}
于 2013-05-21T21:03:18.040 回答