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.");
}
}
添加回答
舉報