How do you detect space in a string? Here is my code, I tried to find the space as a char, but every 1 space, it adds 5 instead of 1. Can anyone explain it to me?
public static void main(String[] args) {
Main main = new Main();
String s = "HELLO WORLD";
System.out.println("Vowel is = "+main.balancedSplitString(s));
}
public int balancedSplitString(String s) {
char vowel[] = {'A', 'I', 'U', 'E', 'O'};
int space = 0;
int result = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < vowel.length; j++) {
/*ignore this part
if (s.charAt(i) == vowel[j]) {
result++;
}*/
else if(s.charAt(i) == ' '){
space++;
}
}
}
System.out.println("Space is = " + space);
return result;
}
You have a nested for loop. For each iteration of the outer loop, the inner loop would have had 5 iterations, because there are five vowels. You can use the "step through" feature of your debugger to check this.
This means that for each value of i
, the thing inside the inner for loop runs 5 times. When i
reaches the index where the space is at, space++
is run 5 times because i
never changes while the inner loop is looping.
To fix this, just move space++
outside of the inner for loop, but still inside the outer for loop:
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < vowel.length; j++) {
/*ignore this part
if (s.charAt(i) == vowel[j]) {
result++;
}*/
}
if(s.charAt(i) == ' '){ // here!
space++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.