2014-03-03 117 views
1

我希望能夠輸出每個單詞的字母大小。到目前爲止,我的代碼只輸出第一個單詞的字母大小。我如何才能輸出剩餘的單詞?如何計算此字符串中每個單詞的大小?

import java.util.*; 

public final class CountLetters { 
    public static void main (String[] args) { 

    Scanner sc = new Scanner(System.in); 
    String words = sc.next(); 
    String[] letters = words.split(" "); 

    for (String str1 : letters) { 
     System.out.println(str1.length()); 
    } 
    } 
} 

回答

1

這只是因爲next只返回的第一個單詞(或也稱爲第一 '令牌'):

String words = sc.next(); 

要讀取整個行,使用nextLine

String words = sc.nextLine(); 

那麼你應該怎麼做才行。

你可以做的另一件事是繼續使用next一路(而不是分裂),因爲掃描儀已經搜索使用空格默認令牌:

while(sc.hasNext()) { 
    System.out.println(sc.next().length()); 
} 
+0

謝謝,這個作品 – user3376304

+0

沒問題!如果問題解決了,請隨時[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – Radiodef

1

使用sc.next()將只允許掃描儀接收第一個單詞。

String words = sc.nextLine(); 
0

遍歷所有的掃描儀值:

public final class CountLetters { 
    public static void main (String[] args) { 
     Scanner sc = new Scanner(System.in); 
     while(sc.hasNext()) { 
      String word = sc.next(); 
      System.out.println(word.length()); 
     } 
    } 
} 
相關問題