2015-12-07 23 views
-2

好的,我的代碼應該打印輸入的單詞總量,最長和最短的單詞。我似乎無法弄清楚如何讓它打印出最短的單詞,總的和最長的工作。我似乎無法讓我的程序打印最短的單詞

public void stringInput() 
{ 
    Scanner keyboard = new Scanner(System.in); 
    int wordcount =0; 
    String word =""; 
    String longest = ""; 
    String shortest = ""; 
    while(! word.equals("DONE")) 
    { 
     System.out.print("Please enter a word or DONE to exit: "); 
     word = keyboard.next(); 
     if(!word.equals("DONE")) 
     { 
      wordcount ++; 
      if (word.length() < shortest.length()) 
       { 
       shortest = word; 
       } 
      if (word.length() > longest.length()) 
      { 
       longest = word; 
      } 
     } 
    } 
    System.out.println("Thank you for entering "+wordcount+" words."); 
    System.out.println("Longest word :"+ longest); 
    System.out.println("Shortest word :"+ shortest); 
} 

回答

3

無字比""較短,所以shortest永遠不會改變。一種修復方法是將shortest設置爲第一個詞,而不是""。另一種方法是更改​​if,以便如果該詞較短或shortest的長度仍爲零,則它將設置爲shortest

另一種可能性:

 if ((wordcount == 1) || (word.length() < shortest.length())) 
     { 
      shortest = word; 
     } 
+0

所以我會用字替換「」? – TheCompile

+0

您可以通過我建議的三種方式(或者augustoccesar建議的方式)來解決這個問題。但是,如果根本沒有詞語,用詞替換「」將不起作用。 –

+0

我很困惑,爲什麼你使用wordcount,如果只是加入了輸入的單詞總量? – TheCompile

0

無字會比一個空字符串短。您應該設置最短爲null並檢查它是否是第一個輸入的字符串,如果是,請將其設置爲最短,然後檢查與第一個字符串比較的所有其他字符串。 像這樣:

while(! word.equals("DONE")) 
{ 
    System.out.print("Please enter a word or DONE to exit: "); 
    word = keyboard.next(); 
    if(!word.equals("DONE")) 
    { 
     if(shortest != null){ 
      if (word.length() < shortest.length()) 
      { 
       shortest = word; 
      } 
     }else{ 
      shortest = word; 
     } 
     if (word.length() > longest.length()) 
     { 
      longest = word; 
     } 
     wordcount ++; 
    } 
} 
+0

我試着將它設置爲null,但它不會運行 – TheCompile

+0

但是解決方案並不是簡單的將最短設置爲null。在比較之前,你必須檢查字符串是否是第一個字符串。去更新我的答案。 – augustoccesar

相關問題