ArrayList:我想在我的arrayList中找到一个词

我有一个包含多个元素的 arrayList:

ArrayList<String> listName = new ArrayList<String>();
    
listName.add("julie");
listName.add("sandrine");
listName.add("toto");

用户输入一个名称,例如popo,该元素不存在。但是,我有几个打印,我不明白?

The word isn't find 
The word isn't find 
The word isn't find 

我试着做一个算法:

import java.util.ArrayList;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    
    ArrayList<String> listName = new ArrayList<String>();
    
    listName.add("julie");
    listName.add("sandrine");
    listName.add("toto");

    System.out.println("please enter your name : ");
    String wordSearch = input.nextLine();

    for (int i = 0; i < listName.size(); i++) {
      if (listName.get(i).equals(wordSearch)){ 
        System.out.println("The word is find : "); 
      } else {
        System.out.println("The word isn't find ");
      }
    }

  }

}

回答

如果只想打印一次,则需要执行以下操作:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    ArrayList<String> listName = new ArrayList<String>();

    listName.add("julie");
    listName.add("sandrine");
    listName.add("toto");

    System.out.println("please enter your name : ");
    String wordSearch = input.nextLine();

    boolean isUserFound = false;
    for (String s : listName) {
        if (s.equals(wordSearch)) {
            isUserFound =true;
            break;
        }
    }
    if(isUserFound)
        System.out.println("The word is find : ");
    else
        System.out.println("The word isn't find : ");
}

首先找出用户是否存在,相应地设置一个标志并相应地打印结果。

或者您可以简单地通过以下方式替换循环:

if(listName.contains(wordSearch))
    System.out.println("The word is find : ");
else
    System.out.println("The word isn't find : ");

或者

if(listName.indexOf(wordSearch) != -1 )
    System.out.println("The word is find : ");
else
    System.out.println("The word isn't find : ");

这两种方法(即, containsindexOf)都是列表集合的一部分,因此您无需重新实现该逻辑,只需使用已有的。

完整示例:

  public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List<String> listName = new ArrayList<>();
        listName.add("julie");
        listName.add("sandrine");
        listName.add("toto");

        System.out.println("please enter your name : ");
        String wordSearch = input.nextLine();

        if(listName.contains(wordSearch))
            System.out.println("The word is find : ");
        else
            System.out.println("The word isn't find : ");
    }


以上是ArrayList:我想在我的arrayList中找到一个词的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>