Rohith L. Rohith L. - 4 months ago 18
Java Question

pig latin-like program - issues with vowels

I'm writing a program that has two rules:
1. If the first character of the word is a vowel, then move it to the end of the word.
2. If the first character of the word is a consonant, then move it to the end of the word and append 'ae'.

import java.util.Scanner;

public class Program5 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String english = scanner.nextLine();
String piggy = piggyEnglish(english);
System.out.print("Translated: " + piggy);
}
private static String piggyEnglish(String s) {
String piggy = "";
int i = 0;
while (i<s.length()) {

while (i<s.length() && !isLetter(s.charAt(i))) {
piggy = piggy + s.charAt(i);
i++;
}

if (i>=s.length()) break;

int begin = i;
while (i<s.length() && isLetter(s.charAt(i))) {
i++;
}

int end = i;
piggy = piggy + piggyWord(s.substring(begin, end));
}
return piggy;
}

private static boolean beginsWithVowel(String word){
String vowels = "aeiou";
char letter = word.charAt(0);
return (vowels.indexOf(letter) != -1);
}

private static boolean isLetter(char c) {
return ( (c >='A' && c <='Z') || (c >='a' && c <='z') );
}

private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split) + word.substring(0, split);
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}

private static int firstVowel(String word) {
word = word.toLowerCase();
for (int i=0; i<word.length(); i++)
if (word.charAt(i)=='a' || word.charAt(i)=='e' ||
word.charAt(i)=='i' || word.charAt(i)=='o' ||
word.charAt(i)=='u')
return i;
return 0;
}
}


The following is the expected output:

Please enter a sentence: today is a beautiful day
Translated: odaytae si a eautifulbae aydae


However, this is what I'm getting:

Please enter a sentence: today is a beautiful day
Translated: odaytae is a eautifulbae aydae


Basically, it doesn't translate any words that start with a vowel. I think the problem stems from the piggyWord method, but I'm not certain. Can I get any pointers on how to fix this?

Answer

The error lies in the piggyWord function:

private static String piggyWord(String word) {
        int split = firstVowel(word);
        if(beginsWithVowel(word)) {
            return word.substring(split + 1) + word.substring(0, split + 1); //Since vowel is in 1st place, substring(0,0) returns empty string.
        } else {
        return word.substring(split) + word.substring(0, split)+"ae";
        }
}   
Comments