user3307598
user3307598

Reputation: 525

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 :)

Upvotes: 0

Views: 50

Answers (2)

Md. Nasir Uddin Bhuiyan
Md. Nasir Uddin Bhuiyan

Reputation: 1596

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");
}

Upvotes: 0

singhakash
singhakash

Reputation: 7919

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.

Upvotes: 2

Related Questions