2016-02-25 106 views
1
的indexOf

所以我想寫一個方法,將返回給我一個字符串出現的次數在另一個字符串。在這種情況下,它會查找字符串中的空格數。就好像indexOf()沒有識別空格。尋找空間在一個字符串在Java中使用

這裏是我的方法:

public int getNumberCardsDealt() 
{ 
    int count = 0; 
    int len2 = dealtCards.length(); 

    int foundIndex = " ".indexOf(dealtCards); 

    if (foundIndex != -1) 
    { 
     count++; 
     foundIndex = " ".indexOf(dealtCards, foundIndex + len2); 
    } 

    return count; 
} 

這裏是我的應用程序:

public class TestDeck 
{ 
public static void main(String [] args) 
{ 
    Deck deck1 = new Deck(); 

    int cards = 52; 
    for(int i = 0; i <= cards; i++) 
    { 
     Card card1 = deck1.deal(); 
     Card card2 = deck1.deal(); 
    } 

    System.out.println(deck1.cardsDealtList()); 
    System.out.println(deck1.getNumberCardsDealt()); 
} 
} 

請注意,我已經有一個Card類和deal方法工作。

+0

請注意,你的方法(即使正確)只會返回0或1.沒有循環,你也可以像'return dealtCards.contains(「」)那樣實現它? 1:0'。 –

回答

2

檢查indexOf方法的文檔。你用錯了。

你應該改變調用

" ".indexOf(dealtCards); 

dealtCards.indexOf(" "); 

也就是說,援引對有關串的方法,並傳遞給它,你正在尋找的,而不是其他方式的字符。


而且,你的方法不會計算它正確無論如何,你應該改變它的東西,如:

public int getNumberCardsDealt() { 
    int count = 0; 
    int foundIndex = -1; // prevent missing the first space if the string starts by a space, as fixed below (in comments) by Andy Turner 

    while ((foundIndex = dealtCards.indexOf(" ", foundIndex + 1)) != -1) { 
     count++; 
    } 

    return count; 
} 
+0

是的,我剛剛意識到,我固定它謝謝 – 21mhi

+1

尼特:你應該用'foundIndex = -1'啓動,否則會錯過字符串中的第一個字符。 –

+0

@AndyTurner很棒!我會相應更新 –

1

@ A.DiMatteo的答案給你的原因,你的indexOf目前不工作。

內部,String.indexOf基本上只是通過人物迭代。如果你總是尋找單個字符,你可以自己做這個迭代自己做計數:

int count = 0; 
for (int i = 0; i < dealtCards.length(); ++i) { 
    if (dealtCards.charAt(i) == ' ') { 
    ++count; 
    } 
} 
相關問題