Write a Java program to input a sentence that must terminate with a full stop or a question mark or an exclamation mark. Now generate a new sentence by converting each word of the original sentence to piglatin.
The following rules are to be followed to convert a word into piglatin:
- For words that start with a consonant: Move the initial consonant cluster to the end of the word and add “AY”. Example: WELCOME becomes ELCOMEWAY.
- For words that start with a vowel: Simply add “AY” to the end of the word. Example: APPLE becomes APPLEAY.
import java.util.Scanner;
class Piglatin{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String s = in.nextLine().toUpperCase();
if(s.length() == 0){
System.out.println("INVALID SENTENCE");
return;
}
char last = s.charAt(s.length() - 1);
if(".?!".indexOf(last) == -1){
System.out.println("INVALID SENTENCE");
return;
}
String p = "";
String word = "";
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetterOrDigit(ch))
word += ch;
else{
ch = s.charAt(i);
if(word.length() > 0)
p += convert(word) + ch;
else
p += ch;
word = "";
}
}
System.out.println(p);
}
public static String convert(String w){
int pos = 0;
for(int i = 0; i < w.length(); i++){
char ch = w.charAt(i);
if("AEIOU".indexOf(ch) >= 0){
pos = i;
break;
}
}
String p = w.substring(pos, w.length());
p += w.substring(0, pos) + "AY";
return p;
}
}