diff --git a/src/main/java/com/levelup/java/exercises/beginner/PigLatin.java b/src/main/java/com/levelup/java/exercises/beginner/PigLatin.java new file mode 100644 index 0000000..5ee5902 --- /dev/null +++ b/src/main/java/com/levelup/java/exercises/beginner/PigLatin.java @@ -0,0 +1,55 @@ +package com.levelup.java.exercises.beginner; + +import java.util.List; +import java.util.Scanner; +import java.util.function.Function; +import java.util.stream.Collectors; + +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; + +/** + * This java example will demonstrate how to convert a phrase to pig latin. + * + * @author Justin Musgrove + * @see Pig latin translator + */ +public class PigLatin { + + public static void main(String[] args) { + // Create a Scanner object for keyboard input. + Scanner keyboard = new Scanner(System.in); + + // Ask user to enter a string to translate + System.out.println("Enter a string to translate to Pig Latin."); + System.out.print("> "); + String input = keyboard.nextLine(); + + // close the keyboard + keyboard.close(); + + List elementsInString = Lists.newArrayList(Splitter.on(" ") + .split(input)); + + Function swapFirstLastChar = new Function() { + @Override + public String apply(String s) { + if (s.length() <= 1) { + return s; + } else { + return s.substring(1, s.length()) + s.charAt(0); + } + } + }; + + List translatedString = elementsInString.stream() + .map(String::trim).map(String::toUpperCase) + .map(swapFirstLastChar).map((String s) -> { + return s + "AY"; + }).collect(Collectors.toList()); + + + System.out.println("Translated sentence is: " + + String.join(" ", translatedString)); + } +} \ No newline at end of file