2017-08-08 123 views
0
public class LongWord { 
    public static void main(String args[]) { 
     String text = "my brother is taller than [email protected] I always a short man,but smart than him"; 

     // Find the longest word in the String 
     String[] words = text.split("\\s"); 
     String longestWord = ""; 
     for (int i = 1; i < words.length; i++) { 
      int firstLen = words[i - 1].length(); 
      int secondLen = words[i].length(); 
      if (firstLen <= secondLen) { 
       longestWord = words[i]; 
      } 
     } 
     System.out 
       .println("===================================================\nLongest Word:::: \n"); 
     System.out.println(longestWord); 
    } 
} 

//這是查找語句中最長單詞的示例程序。所以輸出應該是「me @ 1233334」這個詞。但我得到的是「人,但」字作爲輸出。任何人都可以請幫助我什麼是錯誤的程序。字符串長度()比較不正常

+3

用鋼筆執行你的算法,在peper,寫在每一步中每個變量的值。你有一個基本的邏輯思想。 –

+0

特別關注你正在比較的單詞的長度。 – GhostCat

+0

你可能想看看另一個名爲StringTokenizer的java類。有了它,您可以指定使用哪些分隔符,如空格和逗號。 – Alan

回答

0

你的方法沒有找到字符串數組最大的字符串。它查找字符串數組中的最後一個字符串,它比它之前的字符串大。

您的比較(firstLen <= secondLen)不會比較任何字符串與當前最長的字符串。主循環應該是:

String longestWord = words[0]; 
for(String word : words) { 
    if(word.length() > longestWord.length()){ 
    longestWord = word; 
    } 
} 

您還可以使用for(int i = 0; i < words.length(); i++)和使用words[i]代替(String word : words)word

0

決定最長單詞的邏輯是錯誤的。

您正在比較一個「單詞」(在這種情況下,單詞是指以空格分隔的東西)與前一個單詞,如果它更長,現在是最長的。

男人,但被選中,因爲它只是比它的前一個字(短)更長。請注意,沒有任何東西,但選擇,因爲之後沒有任何單詞比他們以前的單詞長

0

你做錯了。你是不是比較,如果secondLenlongestWord大,它實際上應該是:

longestWord = words[0]; 
for (int i = 1; i < words.length; i++) { 
    int longestLen = longestWord.length(); 
    int secondLen = words[i].length(); 
    if (longestLen <= secondLen) { 
     longestWord = words[i]; 
    } 
}