2016-03-20 47 views
-1

我想找到一個句子中每個單詞的字母數。我已經嘗試了幾次使用幾個代碼,但從來沒有得到它。我總是顯示錯誤StringIndexOutOfBounds異常。我的一個代碼如下:java程序找到一個句子中每個單詞的字母數

import java.util.*; 
    class LengthOfEachWord 
    { 
     public static void main() 
     { 
      Scanner sc = new Scanner(System.in); 
      String s,a,b; 
      int l,x,l1,y=0,now; 
      try 
      { 
       System.out.print("Enter a sentence:"); 
       s=sc.nextLine(); 
       l=s.length(); 
       String arr[]=s.split(" "); 
       now=arr.length; 
       while(true) 
       { 
        x=s.indexOf(' '); 
        a=s.substring(0,x); 
        l1=a.length(); 
        System.out.println(a+"="+l1); 
        b=s.substring(x+1,l); 
        s=b; 
        y++; 
        if(now==y) 
        { 
         break; 
        } 
       }//End of while block 
      }//End of try block 
      catch(Exception e) 
      { 
       System.out.println("Error="+e); 
      } 
     } 
    } 

回答

1

儘量拆分字,並通過迭代計數每個元素的長度的陣列

實施例中:

public static void main(String[] args) { 
    final Scanner myScanner = new Scanner(System.in); 
    String sentence; 
    System.out.print("Enter a sentence:"); 
    sentence = myScanner.nextLine(); 
    // now split by space 
    final String[] sentceComp = sentence.split(" "); 
    // loop over the words in sentence 
    for (int i = 0; i < sentceComp.length; i++) { 
     System.out.println("The word \"" + sentceComp[i] + "\" in the input sentence has " + sentceComp[i].length() + " chars"); 
    } 
} 

輸出:

輸入一句話:

java程序,找出每個單詞的長度在一個句子

在輸入語句的單詞「Java」的具有4個字符

在輸入語句的字「節目」有7個字符

詞語「爲」在輸入語句具有2個字符

單詞 「找到」,在輸入句子有4個字符

的單詞 「the」 在輸入語句有3個字符

在輸入語句的單詞「長度」具有6個字符

「的」這個詞在輸入句子有2個字符

詞語「每個」在輸入句子具有4個字符

在輸入語句的單詞「字」具有4個字符

單詞「中」,在輸入句子有2個字符

的詞語「一」在輸入句子具有1個字符

輸入句子中的「句子」一詞有8個字符

+0

謝謝。你能給一個更簡單一點的程序,而不是使用數組嗎? –

相關問題