How can I improve the pig latin translator java?
Over the last few days I created this Pig Latin Translator just for fun. I would really appreciate it if anybody could give suggestions of how to improve the code and make the program more efficient. Here is the GitHub link for the project The code is in PigLatin.java.
/* -------------------- Program Information -------------------- Name Of Program: PigLatin.java Date of Creation: 7/3/2018 Name of Author(s): Agnik Banerjee Version of Java: 1.8.0_171 Created with: IntelliJ IDEA 2017.3.5 Community Edition -------------------- Program Information -------------------- */ import java.util.Scanner; public class PigLatin { private static Scanner scan = new Scanner(System.in); public static void main(String[] args) { System.out.print("Enter one or more words that you would like to translate to Pig Latin: "); final String userInput = scan.nextLine(); scan.close(); String[] word = userInput.split(" "); // Splits the string into an array of words String output = ""; for (int i = 0; i < word xss=removed xss=removed xss=removed xss=removed>
I would suggest the following points to make your pig latin translator java programme more object-oriented:
Try using a collection object provided by Java instead of using array
String[] word = userInput.split(" ");
could be
List words = Arrays.asList(userInput.split(" "));
or using external library Guava
List words = Splitter.on(" ").splitToList(userInput);
Avoid comments where you can.
In this case I can see you can easily avoid comment if you can wrap up the particular code snippet with the meaningful name. For instance You could take the user input and breaking it in a list in separate class and call the class from your main
List words = new UserInputHandler().getInputAsList();
Try to use foreach loop over for loop:
You can easily use the foreach loop to iterate over words
for (String word : words) { String pigLatinWord = translateWord(word); // Translates each word individually output += pigLatinWord + " "; // Joins the translated word back into the output }
Again as suggested before you can wrap the code inside for loop in a separate class so that you could call
for (String word : words) { output = new PigLatinTranslator(word, output).translate(); }