Domanda

I'm currently working through an AP Computer Science exam study guide and I've hit a brick wall with one of the problems.

    String s = "mathematics";
    String vowels = "aeiou";
    int number = 0;
    for(int i = 0;i<s.length();i++){
        number += s.indexOf(vowels.substring(0));
    }

What is value of number after the code is executed? I came to the conclusion of 11, because the first index of vowels is "a" so the first time that a occurs in s is at index 1. After 11 loops that would result to 11. But for some reason the correct answer is -11. I can understand how it's negative, because it returns -1 whenever its not found within the string. But I'm completely lost as to why thats occurring in this situation. Any help is appreciated!

È stato utile?

Soluzione

First, recognize that vowels.substring(0) doesn't do anything. A substring from position 0 is equivalent to the string itself.

The string vowels, or "aeiou", doesn't appear anywhere in "mathematics", so indexOf will return -1 11 times ("mathematics" is length 11). Therefore, the result of number at the end is -11.

While it's not clear exactly what you want, if you want to get the positions of each of the vowels in the string s, you'll have to re-write your for loop and use charAt(i) or substring(i, i + 1).

Altri suggerimenti

That's because substring(0) returns the complete string.

You can try this to understand:

System.out.println(vowels.substring(0));

The result of vowels.substring(0) is "aeiou", and "aeiou" does not exist in String s ("mathematics").

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top