2014-03-03 71 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()); 
     } 
    } 
} 
相关问题