2015-04-12 29 views
0

我有一個包含一些單詞的列表。例如[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)) 
     { 
      newWord = "True"; 
     } 
     else 
     { 
      newWord = checkWord; 
     } 
    } 
    System.out.println(newWord); 

任何幫助將是巨大的:)

+3

什麼問題? –

+0

忘了提及那部分。它只是直接到IF語句的其他部分,即使我知道checkWord在列表中 – user3307598

回答

2

把一個休息的時候串中發現

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

因爲字符串是否被發現或不循環迭代直到結束,所以如果最後的字符串不是c(輸入的字符串),它將執行else部分。

+1

已經工作了,感謝:D – user3307598

0

有很多方法來找到它:

1:迭代通過列表

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

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

3:如果你想codeWord

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

2串查找位置請參閱codeWord是否存在

if(testList.indexOf(codeWord)>-1){ 
    System.out.println("Found"); 
}else{ 
    System.out.println("Not Found"); 
} 
相關問題