2015-12-14 64 views
1

我只想在末尾獲得'@'和','(或']')之間的數字&;然後將它們添加到數組列表中。爲什麼這不起作用?沒有看到停在逗號...無法從該字符串中獲取正確的子字符串

ArrayList<String> listUsers=new ArrayList<String>(); 

     String userToAdd = new String(); 
     String objectInText; 
     objectInText="[[email protected],[email protected]]"; 

       for (int i=0;i<objectInText.length();i++){ 
      if (objectInText.charAt(i)=='@'){ 
       int j=i; 
       while((objectInText.charAt(j)!=',') || (objectInText.charAt(j)!=']')){ 
        userToAdd+=objectInText.charAt(j+1); 
        j++; 
       } 


       listUsers.add(userToAdd); 
       System.out.println(userToAdd); 
       userToAdd=""; 
      } 
     } 

回答

4
while((objectInText.charAt(j)!=',') || (objectInText.charAt(j)!=']')) 

你循環,直到當前字符不是「」或者它不是‘]’

這基本上意味着環路只有當字符是','和']'時纔會停止,這顯然是不可能的。

你應該替換你的「||」與「& &」,使得while循環繼續,只要j既不是','也不是']'。


注意

我不知道這是否可以幫助你,但如果你知道「@」和「」只有字母和數字(無特殊間字符,因爲你說你只是想字母和數字),你也知道,「@」和「」只出現1次,你也可以做這樣的事情:

int startIndex = objectInText.indexOf('@')+1; 
int endIndex = objectInText.indexOf(','); 
String userToAdd =objectInText.substring(startIndex, endIndex); 
+0

好了,現在笑我的頭太累了。謝謝盧卡斯! – ArtanisAce

+1

while停止,當表達式評估爲false時,這意味着BOTH表達式必須爲假 –

+0

但是,當您使用AND(&&)運算符時,這兩個表達式都必須爲true,也就是說,當它們中的一個爲假時,它會停止。 –

相關問題