2011-03-19 98 views
0

我需要幫助獲取長度大於或等於用戶給定的最小長度的字符串數。 ex:字符串輸入「this is a game」minlength = 2.該句子中3個單詞的長度爲> = minLength,因此輸出應爲3.由於3個單詞爲> = minLength需要String Java幫助

我面對輸出有問題。我輸入一個字符串,將它拆分成單獨的單詞並將它們發送到計算輸出的方法。上面的例子的期望值是3,但是我得到1,1,1。

public class WordCount { 

    /** 
    * @param args 
    */ 

    public static String input; 
    public static int minLength; 

    public static void Input() { 

     System.out.println("Enter String: "); 
     input = IO.readString(); 

     System.out.println("Enter minimum word length: "); 
     minLength = IO.readInt(); 

    } 

    public static void Calc() { 

     Input(); 

     String[] words = input.split(" "); 

     for (String word : words) { 

      LetterCount(word); 
     } 

    } 

    public static int LetterCount(String s) { 


     int countWords = 0; 


     if (s.length() >= minLength) { 

      countWords += 1; 

      IO.outputIntAnswer(countWords); 

     } 



     return countWords; 

    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     Calc(); 

    } 

} 

回答

0

它,因爲你每次只正在重置的countWords變量設置爲零和輸出1.靜態整數持有計數,並打電話給你的輸出功能calc你literated在所有的字符串後。

static int countWords = 0; 
public static void Calc() { 
    Input(); 

    String[] words = input.split(" "); 

    for (String word : words) { 
     LetterCount(word); 
    } 
    IO.outputIntAnswer(countWords); 
} 

public static int LetterCount(String s) { 
    if (s.length() >= minLength) { 
     countWords += 1; 
    } 
    return countWords; 
} 
+0

非常感謝.. – user647207 2011-03-19 22:05:49

1

你非常接近!

您爲每個單詞調用LetterCount,並在LetterCount的開始處將countWords設置爲0.因此,您的計數器每次都會重置!

讓Count不是作爲LetterCount的局部變量而是您的類中的私有變量。

廣場

private static int countWords = 0; 

在文件的頂部。

刪除

int countWords = 0; 
從LetterCount

+1

+1,但該字段應該是** static **,因爲所有OP的方法都是靜態的。另外,OP從方法'LetterCount'返回計數,因此OP有可能在調用者站點消耗返回值,並在那裏增加一個類似的計數變量。最後,打印輸出值IO.outputIntAnswer的調用將不得不移動。 – 2011-03-19 22:02:33

+0

你說得對。我會做出改變。 – Starkey 2011-03-19 22:03:14

+0

他也在錯誤的位置調用輸出語句。只有你的改變,他會得到1,2,3我相信 – Kurru 2011-03-19 22:04:11

0

您每次輸入LetterCount() 時,都會設置countWords = 0您應該從LetterCount()中刪除計數邏輯並將其放在循環的Calc()中。

+0

請告訴他爲什麼要使用while循環?對於循環,它完全適合 – Kurru 2011-03-19 22:06:01

+0

哦,是的,我實際上是在循環,不管它是什麼。對困惑感到抱歉。 – 2011-03-19 22:12:59