Program opened below. You can scroll through the algorithm, Java code and output.
Program 04
Pig Latin Using Recursion
Question
Design a Piglatin class with constructor, input(), recursive convert(), and output(). Move the initial consonants to the end and add ay.
Algorithm
Step 1: Start the program.
Step 2: Create a Piglatin object.
Step 3: Initialize word and newword in the constructor.
Step 4: Accept one alphabetic word using input().
Step 5: Scan its characters to detect whether a vowel exists.
Step 6: If no vowel is present, append ay without rotating.
Step 7: Otherwise call a recursive rotation function with the word.
Step 8: At each recursive call inspect the first character.
Step 9: If the first character is a vowel, return the current string.
Step 10: Otherwise move the first consonant to the end.
Step 11: Call the rotation function again with the modified string.
Step 12: Continue until the first vowel reaches the start.
Step 13: Append ay to the returned string.
Step 14: Display the original and converted forms.
Step 15: Stop the program.
Java program
Javaimport java.util.*;
class Piglatin {
String word;
String newword;
Piglatin() {
word = "";
newword = "";
}
void input() {
Scanner sc = new Scanner(System.in);
word = sc.next();
}
// Rotate initial consonants recursively.
String rotate(String s) {
if (s.length() == 0) {
return s;
}
char ch = Character.toUpperCase(s.charAt(0));
if ("AEIOU".indexOf(ch) >= 0) {
return s;
}
return rotate(s.substring(1) + s.charAt(0));
}
void convert() {
boolean vowel = false;
for (int i = 0; i < word.length(); i++) {
char ch = Character.toUpperCase(word.charAt(i));
if ("AEIOU".indexOf(ch) >= 0) {
vowel = true;
}
}
newword = vowel ? rotate(word) + "ay" : word + "ay";
}
void output() {
System.out.println(word + " -> " + newword);
}
public static void main(String[] args) {
Piglatin ob = new Piglatin();
ob.input();
ob.convert();
ob.output();
}
}Sample output
Input: CHAIR
Output: CHAIR -> AIRCHay