如何允许用户搜索元素

时间:2016-08-28 22:22:21

标签: java

我创建了一个小型测试类,它使用Set接口来删除列表中的重复项。我如何让用户搜索此列表?

以下是我目前的程序:

**更新我已经为搜索功能创建了一个方法,有一个错误会破坏程序。

/*
 * This program will read a series of first names and eliminate duplicates
 * by storing them in a Set. Allow the user to search for a first name.
 * 
 */
package Exercises;

/**
 * 8/25/2016
 * @author Demond
 */
import java.util.List;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Collection;
import java.util.Scanner;

public class Duplicate_Elimination2
{

    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args)
    {
        String[] names = {"Demond", "Demond", "Joe", "Rose", "Ashely"};
        List<String> list = Arrays.asList(names);
        System.out.printf("List: %s%n", list);

        printNonDuplicates(list);
        searchNames(names);
    }

    private static void printNonDuplicates(Collection<String> values)
    {
        Set<String> set = new HashSet<>(values);

        System.out.printf("%nNonduplicates are: ");

        for (String value : set)
            System.out.printf("%s ", value);

        System.out.println();
    }

     // search names from list
   private static void searchNames(String[] names)
   {
      // get name from standard input
      System.out.println(
         "Search a name, type end to stop search:");
      String inputName = scanner.next();

      // obtain input until end entered
      while (!inputName.equals("end"))
      {
         // name found
         if (names.contains(inputName))
            System.out.println(inputName + " found in set");
         else  // name not found
            System.out.println(inputName + " not found in set");

         // get next search name
         System.out.println(
            "Search a name, type end to stop search:");
         inputName = scanner.next();
      }
   } 
}

1 个答案:

答案 0 :(得分:0)

您无法在.contains()上致电String[]

解决方案是将列表传递给searchNames()

searchNames(list);

...然后在searchNames方法中更改参数类型:

private static void searchNames(List<String> names) {

当然,您的搜索执行完全匹配,因此如果您没有完全正确的拼写和大小写,则无法找到该名称。