0

Im trying to reverse only the vowels of a string but it's just not happening. :-( Can anyone tell why is it so.

public class Program { public static boolean isVowel(String a) { String [] vowels = {"a","e","i","o","u"}; int j=0; int len = vowels.length; for(int i=0;i<len;i++) { if(a==vowels[i]) { j++; //break; } } if(j>0) return true; else return false; } public static void main(String[] args) { int z=0; String temp; String sent = "hellokitty"; String [] arr = sent.split(""); int len1 = arr.length-1; int las = len1; for(int k=0;k<len1/2;k++) { for(int i=z;i<=len1;i++) { if(isVowel(arr[i])==true) { z=i+1;; break; } } for(int j=las;j>=0;j--) { if(isVowel(arr[j])==true) { las=j-1;; break; } } temp = arr[z]; arr[z]=arr[las]; arr[las]=temp; } for(int l=0;l<=len1;l++) { System.out.print(arr[l]); } } }

18th Jul 2017, 11:36 AM
Joseph Nithish
Joseph Nithish - avatar
1 Respuesta
+ 1
This should be a compile error. You have an extra semi-colon at "z=i+1;;" Same thing in the other loop with las. I'm not sure why you decided to use .split(""); I'm pretty sure that will leave an empty space on index 0 and index length()-1. Anywho, This is an approach which I think you should consider: Use a loop to find: if the charAt(i) in myString is a vowel. I must be aware of its index. So, if wanted you could use an array for all the index's of the vowels. By the looks of it you're only attempting to swap 2 vowels with all those loops. Then you use a loop to reverse the order of these index's on the string. The issue you were having is likely that k and las aren't at the correct index. I'm not sure the logic behind this, but you were incrementing it each time a vowel was found, and using it as an index of the vowel. Minor thing: j in your isVowel method really isn't needed. Instead of "j++; break" just put return true. Then at the end of the method put return false. Makes things easier to read and more optimal.
18th Jul 2017, 3:26 PM
Rrestoring faith
Rrestoring faith - avatar