2014-06-25 136 views
0

我需要一些幫助,這裏與我的java學校工作。 我們被告知要提示用戶輸入五個單詞,然後從中確定最長的單詞並打印以控制最長的單詞以及其中的字符數。Java SE數組幫助需要請

現在,我只設法通過顯示最長的字符數來排列它們,但我不知道如何顯示這個詞本身。有人可以幫助我,請記住我是編程的總新手,我的進步仍然只是在基礎知識,所以請儘量不要讓我太複雜。另外,隨時查找那些冗餘代碼,因爲我知道我有很多。 :) 謝謝!

import java.util.Scanner; 
    import java.util.Arrays; 

    class LongestWord 
    { 
public static void main(String [] args) 
{  
    Scanner theInput = new Scanner(System.in); 
    System.out.println("Please enter your five words"); 

    String fWord = theInput.next(); 
    String sWord = theInput.next(); 
    String tWord = theInput.next(); 
    String fhWord = theInput.next(); 
    String ffWord = theInput.next(); 

    System.out.println(fWord + sWord + tWord + fhWord + ffWord); 

    int [] wordCount = new int[5]; 

    wordCount[0] = fWord.length(); 
    wordCount[1] = sWord.length(); 
    wordCount[2] = tWord.length(); 
    wordCount[3] = fhWord.length(); 
    wordCount[4] = ffWord.length(); 

    Arrays.sort(wordCount); 

    System.out.println(wordCount[4]); 


} 
    } 
+1

您不需要排序只是爲了找到最長的單詞,也不需要將所有單詞存儲在內存中。逐一閱讀,只存儲到目前爲止最長的單詞。 – Henry

+1

你做得很好,只是多想一點,你應該可以自己編寫代碼! – Abubakkar

回答

3

您需要將所有字符串添加到數組,並迭代所有這些字符串。

樣本:

String [] wordCount = new String[5]; 

    wordCount[0] = fWord; 
    wordCount[1] = sWord; 
    wordCount[2] = tWord; 
    wordCount[3] = fhWord; 
    wordCount[4] = ffWord; 

    String longest = ""; 

    longest = wordCount[0]; //get the first array of words for checking 

    for(String s : wordCount) //iterate to all the array of words 
    { 
     if(longest.length() < s.length()) //check if the last longest word is greater than the current workd 
      longest = s; //if the current word is longer then make it the longest word 
    } 

    System.out.println("Longest Word: " + longest + " lenght: " + longest.length()); 

結果:

Please enter your five words 
12345 
1234 
123 
12 
1 
123451234123121 
Longest Word: 12345 lenght: 5 
+0

嗨嗨Rod,感謝您的幫助,但我仍然無法得到它。這部分你說的(String s:wordCount),當我編譯時,它說需要的字符串找到int,不兼容的類型。謝謝! –

+0

@ alan_ogz83 editted見上面評論 –

+0

感謝棒但它仍然無法編譯。現在它仍然說不兼容的類型需要字符串找到整型,但它聲明在你鍵入的區域wordCount [0] = fWord.length();向前。 :) –

2

您需要將所有的字存儲到陣列,並得到最大值排序後根據其長度。

String[] words = ....//Store all words into this array. 

Arrays.sort(words, new Comparator<String>() { 

     @Override 
     public int compare(String o1, String o2) { 
      return o2.length() - o1.length(); 
     } 
    }); 

System.out.println(words[0]); 

,或者,如果您使用Java的8比你更容易得到的結果,

String longWord= 
     Arrays.stream(words).max((o1, o2)->o1.length()-o2.length()).get(); 
0

而不是把長到一個數組,你應該把所有詞語的數組,然後使用for/while循環它們並檢查每個字符串的長度與前一個字符串的比較以記錄最大長度字符串。

或者另一種方式可能是使用循環讀取字符串,並且可以執行相同的邏輯來比較長度而不使用額外的數組。