匹配数组中的字符串

时间:2017-12-13 14:07:58

标签: java arrays

我正在尝试将java中的用户输入与数组列表进行匹配,我正在尝试下面的代码,但它不起作用:

创建我的数组列表:

public ArrayList <Member> members;

public ChristmasClub() {
    this.members = new ArrayList<Member>();
}

检查结果是否与数组列表匹配:

System.out.println("Please enter a name you would like to search for: ");
String search = user_input.next();
List<String> list = Arrays.asList(Member);

if(list.contains(search)){
System.out.println("Match");
}else{
System.out.println("Fail");
}

我如何创建成员:

Member gary = new Member("gary", 25);

2 个答案:

答案 0 :(得分:0)

您希望匹配Member类的属性,假设名称为

class Member {
  private String name;
  private int age;
  public Member(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }
}


public static void main(String[] args) {
  System.out.println("Please enter a name you would like to search for: ");
  String search = user_input.next();
  List<Member> list = Arrays.asList(
         new Member("gary", 25), 
         new Member("anotherGuy", 25));

  if(list.stream().anyMatch(m -> search.equals(m.getName()))) {
    System.out.println("Match");
  } else {
    System.out.println("Fail");
  }
}

答案 1 :(得分:-1)

你做什么接缝与关键字完美匹配。 如果你想搜索字符串中是否包含关键字, 这样做。

String search = user_input.next();
List<String> list = Arrays.asList(Member);

for(String s : list) {
   if(s.contains(search)){
     System.out.println("Match");
     return;
   }
}
System.out.println("Fail");