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.
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 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.