简体   繁体   中英

I am trying to see if an element of my list equals a variable

I have a list that contains some words. For example [a,b,c,d,e,f]. I am trying to make is so that if I have a string "c", I can iterate through the list until "c" is found and it will tell me it's position in the list.

This is my code so far

    String checkWord = "c";
    String newWord = "";
    for(int i = 0; i < testList.size(); i++)
    {

        if(testList.get(i).equals(checkWord))
        {
            newWord = "True";
        }
        else
        {
            newWord = checkWord;
        }
    }
    System.out.println(newWord);

Any help would be great :)

Put a break when string is found

  String checkWord = "c";
  String newWord = "";
  for (int i = 0; i < testList.size(); i++) {

    if (testList.get(i).equals(checkWord)) {
        newWord = "True";
        break;
    } else {
        newWord = checkWord;
    }
  }
  System.out.println(newWord);

Because whether the string is found or not the loop iterats till the end so if the last string is not c (the entered string) it will execute the else part.

There are many ways to find it out:

1: Finding position of string codeWord

System.out.println(testList.indexOf(checkWord));//this will print out position of string "c"

2: Iterating through the list

for(int i = 0; i < testList.size(); i++)
    {

    if(testList.get(i).equals(checkWord))
    {
        System.out.println(i);
    }
}

3:If you want to see the codeWord is exists or not

if(testList.indexOf(codeWord)>-1){
    System.out.println("Found");
}else{
    System.out.println("Not 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM