我希望能够输出每个单词的字母大小。到目前为止,我的代码仅输出第一个单词的字母大小。我如何让它输出其余的单词?
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() );
}
}
}
最佳答案
只是因为next
仅返回第一个单词(或也称为第一个“标记”):
String words = sc.next();
要读取整行,请使用nextLine
:
String words = sc.nextLine();
那么你正在做的事情应该会起作用。
您可以做的另一件事是继续使用 next
一路(而不是分割),因为 Scanner 已经默认使用空格搜索标记:
while(sc.hasNext()) {
System.out.println(sc.next().length());
}
关于java - 如何计算该字符串中每个单词的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155775/