3 回答
TA贡献1803条经验 获得超3个赞
迭代wordArray您创建的变量,而不是sentencefor 循环中的原始字符串:
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
String[] wordArray = sentence.trim().split("\\s+");
// String[] wordArray = sentence.split(" "); This would work fine for your example sentence
int wordCount = wordArray.length;
for (int i = 0; i < wordCount; i++) {
int wordNumber = i + 1;
System.out.println(wordNumber + " " + wordArray[i]);
}
System.out.println("Total is " + wordCount + " words.");
}
}
输出:
1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.
TA贡献1951条经验 获得超3个赞
尽量避免过于复杂,下面的就行了
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
int ctr = 0;
for (String str : sentence.trim().split("\\s+")) {
System.out.println(++ctr + "" + str) ;
}
System.out.println("Total is " + ctr + " words.");
}
}
TA贡献1835条经验 获得超7个赞
使用 IntStream 而不是 for 循环的更优雅的解决方案:
import java.util.stream.IntStream;
public class ExampleSolution
{
public static void main(String[] args)
{
String sentence = "This is my sentence and it is not great";
String[] splitted = sentence.split("\\s+");
IntStream.range(0, splitted.length)
.mapToObj(i -> (i + 1) + " " + splitted[i])
.forEach(System.out::println);
System.out.println("Total is " + splitted.length + " words.");
}
}
添加回答
举报