Write an interactive program called PigLatin that reads strings input by the use
ID: 3829312 • Letter: W
Question
Write an interactive program called PigLatin that reads strings input by the user, converts each string into “Pig Latin”, and then prints it out. Pig Latin is English with the initial consonant sound moved to the end of each word, followed by “ay.” Words that begin with vowels simply have an “ay” appended. For example, the words:
would have the following appearances in Pig Latin:
Terminate the program when the user types a blank line (HINT: the isEmpty method of the String class will return true you if the String object you call isEmpty on has no characters in it).
For special sounds, the only one to concern yourself with is words that have an 'h' character as their second letter. Words like: sharp, chirp, thought, etc. For these the sh, ch, th, etc. prefix should be moved to the end as in the sharp example above.
You should implement your logic for converting the String to pig Latin in a method named pigLatinize which has one parameter, a String to pig latin-ize, and returns the pig latin-ized String. You should not print out the string in the pigLatinize method. Printing out should only be done from where you cal the pigLatinize method.
One method we did not implement in class that would be helpful to you is a method that determines if a String object begins with a vowel. You can copy and paste this method into your class and use it as appropriate.
The || operator is the 'or' operator. The expression in that method returns true of any of the sub-expressions, the startsWith method calls, are true (e.g. if s.startsWith("a") OR s.startsWith("e") OR s.startsWith("i") OR ...).
Explanation / Answer
PigLatin.java
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the word: ");
String s = scan.nextLine();
while(!s.isEmpty()){
System.out.println(pigLatinize(s));
System.out.print("Enter the word: ");
s = scan.nextLine();
}
}
public static String pigLatinize(String s){
if(startsWithVowel(s)) {
return s+"-ay";
}
else{
String newStr = "";
if(s.length()>1){
if(s.charAt(1) =='h'){
newStr = s.substring(2);
newStr = newStr+"-"+s.substring(0,2)+"ay";
}
else {
newStr = s.substring(1);
newStr = newStr+"-"+s.charAt(0)+"ay";
}
return newStr;
}
else{
return s;
}
}
}
public static boolean startsWithVowel(String s) {
return s.startsWith("a") || s.startsWith("e") || s.startsWith("i")
|| s.startsWith("o") || s.startsWith("u");
}
}
Output:
Enter the word: mushroom
ushroom-may
Enter the word: sharp
arp-shay
Enter the word: apple
apple-ay
Enter the word:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.