英文:
How can I find the indexPoint in this list?
问题
Letter: a
Words: the
Count = 0
Letter: a
Words: quick
Count = 0
Letter: a
Words: brown
Count = 0
Letter: a
Words: fox
Count = 0
...
英文:
Currently I'm working on this assignment where I need to check if a letter occurs in a word. I've already figured out on how to print the right letter and count. But I'm struggling on how to print the word where the letter in occurs. Would be great if somebody is able to give me some tips. Thanks!
public class joejoe {
public static void main(String[] args) {
String sentence = "the quick brown fox jumps over the lazy dog";
String[] sentenceList = {"the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"};
char[] alphabetList = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
System.out.println("The sentence: \"" + sentence + "\" contains:");
int count = 0;
for (int i = 0; i < alphabetList.length; i++) {
for (int j = 0; j < sentenceList.length; j++) {
String word = sentenceList[j];
for (int k = 0; k < word.length(); k++) {
if (alphabetList[i] == sentence.charAt(j)) {
count++;
}
}
System.out.println("Letter: " + alphabetList[i]);
System.out.println("Words: " + word);
System.out.println("Count = " + count);
count = 0;
}
}
}
}
My output:
Letter: a
Words: the
Count = 0
Letter: a
Words: quick
Count = 0
Letter: a
Words: brown
Count = 0
Letter: a
Words: fox
Count = 0
...
</details>
# 答案1
**得分**: 1
我猜逐句遍历sentenceList,然后逐字遍历每个单词会更容易,这样您可以跟踪单词索引。
```java
for (int i = 0; i < alphabetList.length; i++) {
...
for (int j = 0; j < sentenceList.length; j++) {
String word = sentenceList[j];
...
for (int k = 0; k < word.length(); k++) {
...
}
}
...
}
英文:
I guess would be easier to iterate over sentenceList and then over the letter of each word so you can keep track of word indexes.
for (int i = 0; i < alphabetList.length; i++) {
...
for (int j = 0; j < sentenceList.length; j++) {
String word = sentenceList[j];
...
for (int k = 0; k < word.length(); k++) {
...
}
}
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论