Here I separate a string into separate words and then add "ay"
to the end of each word if it contains a vowel, however the problem is when I reach the last word indexOf
is -1
so it is automaticly skipped by my if statement. To fix this I tried adding an if (i ==-1)
however when I stepped through it with the debugger it automatically skips this if statement! Does anybody know why? And how can work around this issue and add "ay"
to the last word even if .indexOf is -1
Method:
public static void pigLatin(String sentence){
sentence = sentence.trim();
if(sentence.length()> 0){
int i = sentence.indexOf(" ");
String word = sentence.substring(0, i);
if(i == -1){ //this if statement is ignored
if (word.contains("a") || word.contains("i") || word.contains("o") || word.contains("e") || word.contains("u")){
System.out.println(word + "ay");
} else{
System.out.println(word);
}
}
if(i != -1){
if(word.contains("a") || word.contains("i") || word.contains("o") || word.contains("e") || word.contains("u")){
System.out.println(word + "ay");
pigLatin(sentence.substring(i));
} else if(!word.contains("a") || !word.contains("i") || !word.contains("o") || !word.contains("e") || !word.contains("u")){
System.out.println(word);
pigLatin(sentence.substring(i));
}
}
}
}
Main:
public class Main {
public static void main (String [] args){
Scanner in = new Scanner(System.in);
String word = in.nextLine();
Functions.pigLatin(word);
}
}