I made a small test class that uses the Set interface to get rid of duplicates in a list. How would I be able to have a user search this list?
Below is the program I have so far:
**Updated I have made a method for the search function, there is an error that breaks the program.
/*
* 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();
}
}
}
You can't call .contains()
on a String[]
.
The solution is to pass the list to searchNames()
:
searchNames(list);
... and then change the parameter type in your searchNames
method:
private static void searchNames(List<String> names) {
Of course, your search is performing an exact match, so if you don't get the spelling and capitalisation exactly correct, the name won't be found.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.