Java 我想看看列表中的一个元素是否等于一个变量
我有一个包含一些单词的列表。例如[a,b,c,d,e,f]。我想做的是,如果我有一个字符串“c”,我可以遍历列表,直到找到“c”,它会告诉我它在列表中的位置 这是到目前为止我的代码Java 我想看看列表中的一个元素是否等于一个变量,java,Java,我有一个包含一些单词的列表。例如[a,b,c,d,e,f]。我想做的是,如果我有一个字符串“c”,我可以遍历列表,直到找到“c”,它会告诉我它在列表中的位置 这是到目前为止我的代码 String checkWord = "c"; String newWord = ""; for(int i = 0; i < testList.size(); i++) { if(testList.get(i).equals(checkWord))
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);
String checkWord=“c”;
字符串newWord=“”;
对于(int i=0;i
任何帮助都会很好:)找到字符串时请暂停
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);
String checkWord=“c”;
字符串newWord=“”;
对于(int i=0;i
因为无论是否找到字符串,循环都会迭代到结束,因此如果最后一个字符串不是c
(输入的字符串),它将执行else部分。有很多方法可以找到它:
1:查找字符串码字的位置
2:遍历列表
忘了提那部分。它直接转到IF语句的else部分,尽管我知道checkWord在列表中
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);
}
}
if(testList.indexOf(codeWord)>-1){
System.out.println("Found");
}else{
System.out.println("Not Found");
}