Reputation: 525
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
Reputation: 1596
codeWord
System.out.println(testList.indexOf(checkWord));//this will print out position of string "c"
for(int i = 0; i < testList.size(); i++)
{
if(testList.get(i).equals(checkWord))
{
System.out.println(i);
}
}
codeWord
is exists or notif(testList.indexOf(codeWord)>-1){
System.out.println("Found");
}else{
System.out.println("Not Found");
}
Upvotes: 0
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