2015-07-19 46 views
0

我是新來的java編程。這段代碼計算每個單詞中的字母數量並將其存儲爲一個字符串(不包括空格),但它只計算到「大」並且不計算「容器」中的字母數量。字數在句子中不計數最後一個字

class piSong 
{ 
    String pi = "31415926535897932384626433833"; 
    public void isPiSong(String exp) 
    { 
     int i,count=0; 
     String counter = ""; 
     String str; 
     System.out.println(exp.charAt(25)); 
     for(i=0;i<exp.length()-1;i++) 
     { 
      if(Character.isWhitespace(exp.charAt(i))) 
      { str = Integer.toString(count); 
       counter += str; 
       count = 0; 
       continue; 
      } 
      count++; 

     } 
     System.out.println(counter); 
    } 
} 
public class isPiSong{ 
    public static void main(String[] args) 
    { 
     piSong p = new piSong(); 
     String exp = "can i have a large container"; 
     p.isPiSong(exp); 
    } 
} 

預期輸出:314157

電流輸出:31415

+0

隨着您重新學習,堅持[Java命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html)將是明智之舉。用駱駝命名類名,不是用Java編碼的方式:-)編碼時玩得開心:-) –

回答

3

有兩件事情你應該可以解決。

  1. 在你的循環,你的條件是i<exp.length()-1。爲什麼?你顯然想要包含最後一個字符(它是charAt(exp.length() -1)),所以你的條件應該是i <= exp.length() -1i < exp.length()

  2. 您的邏輯是每當遇到空白時計算字母。但在計算最後一個單詞之後,你不會有空白。這就是爲什麼它不包括最後一個字。

要解決,在循環之後追加countcounter

// Loop ends here 
counter += count; 
System.out.println(counter); 
+0

謝謝ton..helped很多:) –

0
String counter = ""; 
String[] array = exp.split(" "); 
for(String s: array){ 
    counter += Integer.toString(s.length); 
} 

第二行分割字符串成字符串(使用在字符串的空間的每個實例拆分)的陣列。循環遍歷數組中的每個單獨的字符串,並將其長度添加到計數器字符串中。 最好使用StringBuilder而不是+=附加到字符串。

StringBuilder sb = new StringBuilder(); 
    String[] array = exp.split(" "); 
    for(String s: array){ 
     sb.append(Integer.toString(s.length)); 
    } 
String counter = sb.toString(); 

但兩者都會這樣做。

相關問題