2013-11-26 43 views
-1

下面是我爲簡單數組問題的代碼,我必須將一個字符串放入一個數組(完成),然後掃描數組以獲得唯一的單詞,將它們放入單獨的數組中,然後計算多少在第三個和最後一個數組中的字符串中存在單獨的唯一字。我可以得到它打印出字符串,但它並計算每個單詞但不是唯一的單詞。我相信問題在於if語句或uwords增量。 任何幫助表示讚賞,但我寧願暗示的答案,而不僅僅是如果可能的答案!使用其他數組的數組增量使用

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

String[] uwords = new String[words.length]; 
int[] wordcount = new int[words.length]; 

for(int i=0; i<words.length; i++){ 
      for(int e = 0; i<words.length; e++){ //loop to count individual words 
       if(words[i].equals(uwords[e])){ //If word in array is contained in the unique words arrary then increment 
        wordcount[wordcounter] = wordcounter+ 1; 
       }else{ //else (word is not contained in uwords) add to uwords and increment 
        uwords[e] = words[i]; 
        wordcount[i] = wordcount[ + 1]; 
       } 

      } 

      System.out.println(uwords[i] + ": " + wordcount[i]); 

Pesudocode是:

Find unique words: 
    Create unique word array 
    Create unique word count array 
    For every word in text 
     if word exists in unique word array 
      Increment corresponding count in unique word count array 
     else 
      Add new unique word in unique word array 
      Increment corresponding count in unique word count array 

List all unique words 
+0

在布穀鳥藍莓蒼蠅,並在收費橋下哈希派所在。 –

回答

2

首先

for(int e = 0; i<words.length; e++) 

是一個無限循環

還有一個更簡單的方法來做到這一點。只需使用一組(Set<String> set = new Set<String>()) 遍歷單詞數組一次,並將其全部添加到該集合中,它將自動添加尚未在其中的單詞。

然後,您可以繼續調用集合中的每個項目,併爲每個循環輸出一個。 它也有一個長度屬性來獲取單詞的數量。

+0

我想我需要使用數組來完成它,如果它有幫助,我已經添加了pesudocode!也改變了那個無限循環,所以e

0

一般來說,兩個或更多個「平行」的陣列,其中在對應的索引的元素要針對單一對象的用法,是不好的設計實踐。

我想嘗試使用一個Map<String, Integer>,其中每個鍵是一個唯一的單詞,其相關的值是它的計數。然後,循環將是簡單的:

Map<String, Integer> uWords = new HashMap<String, Integer>(); 
for(int i=0; i<words.length; i++){ 
    String uWord = uWords.get(words[i]) 
    Integer count = uWords.get(uWord); 
    if(count != null){ 
     count++; 
    } 
    else{ 
     count = 1; 
    } 
    uWords.put(uWord,count); 
} 

然後,您可以處理您在千元Map辦法找到你所需要的。

+0

嘿,謝謝你的回答,即時編程第一年的課程,我們剛剛被介紹給數組,所以它沒有任何先進的! –

0

感謝您提供僞代碼,它使得它更容易回答。問題是,

if word exists in unique word array 
     Increment corresponding count in unique word count array 
    else 
     Add new unique word in unique word array 
     Increment corresponding count in unique word count array 

不會通過所有的話對應

您需要第一迴路uwords評估布爾表達式word exists in unique array然後 if語句做。