Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Main {
- /**
- *This program takes a string given by the user and converts it to pig latin
- */
- public static void main(String[] args) {
- System.out.println("Please insert a sentence to be translated"); //asks the user for input
- Scanner scan = new Scanner(System.in);
- String original = scan.nextLine();
- String translation = translateSentence(original); //translates it using a function
- System.out.println(translation); //prints the result
- }
- /**
- * This translates a whole sentence by using translateWord
- * @param str - user input
- * @return result, translated sentence
- */
- public static String translateSentence(String str){
- int lastSpace = 0;
- String result = "";
- for(int x = 0; x < str.length(); x++){
- if(str.charAt(x) == ' '){ //separates words based on spaces
- String word = str.substring(lastSpace, x);
- String translation = translateWord(word);
- result = result + translation + " "; //adds translated word to the sentence
- lastSpace = x + 1;
- }else if(x == str.length() - 1){ //last word in the string
- String word = str.substring(lastSpace, x + 1);
- String translation = translateWord(word);
- result = result + translation + " "; //adds translated word to the sentence
- lastSpace = x + 1;
- }
- }
- return result;
- }
- /**
- * Translates a single word
- * @param str - the word to be translated
- * @return result - translated string
- */
- public static String translateWord(String str){
- String result;
- String endPart;
- for(int x = 0; x < str.length(); x++){ //goes through the string looking for vowels
- if(isVowel(str.charAt(x))){
- endPart = str.substring(0, x); //if there is a vowel, that's the limit
- result = str.substring(x);
- endPart = endPart + "ay"; //add the part before the vowel with an "ay" to the end
- result = result + "-" + endPart;
- return result;
- }
- }
- //if there isn't a vowel, check for "y"
- for(int x = 0; x < str.length(); x++){
- if(str.charAt(x) == 'y'||str.charAt(x) == 'Y'){
- endPart = str.substring(0, x);
- result = str.substring(x);
- endPart = endPart + "ay";
- result = result + "-" + endPart;
- return result;
- }
- }
- //if there aren't any vowels or "y", just add "-ay"
- result = str + "-ay";
- return result;
- }
- /**
- * Returns whether a character is a vowel
- * @param b the character to be analyzed
- * @return if it is a vowel
- */
- public static boolean isVowel(char b){
- if(b == 'a'||b == 'e'||b == 'i'||b == 'o'||b == 'u'||b == 'A'||b == 'E'||b == 'I'||b == 'O'||b == 'U'){
- return true;
- }else{
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement