怎样才能在这个列表中找到 indexPoint?

huangapple go评论77阅读模式
英文:

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 &lt; alphabetList.length; i++) {
    
    ...

    for (int j = 0; j &lt; sentenceList.length; j++) {
        String word = sentenceList[j];

        ...

        for (int k = 0; k &lt; word.length(); k++) {
           
            ...

        }
    }
    
    ...

}

huangapple
  • 本文由 发表于 2020年10月4日 02:19:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64187515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定