Reputation: 383
this is my code, where i am just reversing the loop and then increasing the counter such that for the first occurrence the count value is 1 and hence skips the println() case. After this, in the second occurrence it will go to the nested if case and just print the index of the second last vowel.
class Main {
public static void main(String[] args) {
int count=0;
String str = "corresponding";
for(int i=str.length();i>=0;i--){
if(i=='a' || i=='e' ||i =='i'|| i=='o'|| i=='u'){
count +=1;
if(count==2)
System.out.println(i);
else
continue;
}
else
continue;
}
}
}
I am not able to print due to some minor logical error which i am not able to figure out. Can anyone help me here.
Upvotes: 1
Views: 149
Reputation: 496
You are comparing i to the vowel character instead of comparing the character from the String, so you should do this:
char c = str.charAt(i);
if (c=='a' || c=='e' ||c =='i'|| c=='o'|| c=='u')
Please also take note that i should start from str.length()-1
Upvotes: 3
Reputation: 20901
To begin, you should heed the starting index which throws an exception as you access elements of the array. You don't get the error just for now since you don't access the elements. Let's try to access them by using the charAt
method.
Upvotes: 1