Hello everyone i am having trouble with this program that i am writing. The purpose of this program is to convert a string entered by a user into pig latin.
The rules of Pig Latin are,
No vowels in the English word, then the Pig Latin word is just the English word + "ay"
If the English word begins with a vowel, then the Pig Latin word is just the English word + "yay".
Otherwise (if the English word has a vowel in it and yet doesn't start with a vowel), then the Pig Latin word is end + start + "ay
When i run this program and i test phrases like "I green" i get "Iyay greenay".
here is my program
Code:/** * This program translate a string into Pig Latin */ import java.util.*; import java.io.*; public class Piglatinator { public static void main(String []args) throws IOException { System.out.println("This program translate a string into Pig Latin"); System.out.println("To end this program at any time just enter \"q\""); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = ""; do { System.out.println("\nPlease enter a string"); str = in.readLine(); System.out.print(translateToPiglatin(str)); } while (!str.equalsIgnoreCase("q") && !str.equalsIgnoreCase("quit")); } public static String translateToPiglatin(String str) throws IOException { StringTokenizer st = new StringTokenizer(str); int num = st.countTokens(); String [] word = new String [num]; int counter = 0; String s = ""; while (st.hasMoreTokens()) { word [counter] = st.nextToken(); if(calculateVowelPositions(word [counter]) == 0) { word[counter] = word[counter].concat("yay"); } else if(word[counter].charAt(0) == 'a' || word[counter].charAt(0) == 'A' || word[counter].charAt(0) == 'e' || word[counter].charAt(0) == 'E' || word[counter].charAt(0) == 'i' || word[counter].charAt(0) == 'I' || word[counter].charAt(0) == 'o' || word[counter].charAt(0) == 'O' || word[counter].charAt(0) == 'u' || word[counter].charAt(0) == 'U') { word[counter] = str.toLowerCase(); word[counter] = str.concat("ay"); } else { int vowel = calculateVowelPositions(str); String end = word[counter].substring(0, vowel); String front = word[counter].substring(vowel , word[counter].length()); front = front + end + "ay"; word [counter] = front; } s = s.concat(word [counter] + " "); counter ++; } return s; } public static int calculateVowelPositions(String str) { str = str.toLowerCase(); str = str.trim(); int position = 0; for(int j = 0; j < str.length(); j ++) { if(str.charAt(j) == 'a') { position = j; break; } else if (str.charAt(j) == 'e') { position = j; break; } else if (str.charAt(j) == 'i') { position = j; break; } else if(str.charAt(j) == 'o') { position = j; break; } else if(str.charAt(j) == 'u') { position = j; break; } } return position; } }


Reply With Quote


Bookmarks