For starters, I'm a student taking AP Computer Science this year, loving it so far. Lots of fun, especially problems like this. I think I'm going to make it a regular practice to post some of my exercises and projects here for people to review, so I can get some feedback from programmers other than my teacher on different ways to do things, ways to clean up my code, and good practice.
I'm not looking for answers here. I've completely written the code and am just looking for some feedback on a few questions listed below.
The prompt is as follows:
Write an interactive program that reads lines of input from the user and converts each line into Pig Latin. Terminate the program when the user types a blank line.
- Words beginning with consonants have the consonant moved to the end of the word and "ay" appended
- Words beginning with vowels simply have "ay" appended
Specific questions:
- Did I do this in an acceptably efficient way? What other, possibly better, ways could I have accomplished this?
- How could this be done without an
ArrayList
? Learning how to useArrayList
s is something I've done on my own time, not that we've learned in class, and I want to become more independent from them on problems like this in case my teacher doesn't want me to keep using them. - What variables do I need to keep as class variables? When I was declaring them I wasn't sure exactly how I would structure the program, or if I was going to organize it into separate methods or not.
import java.util.*;
public class PigLatin {
static ArrayList<String> al = new ArrayList<String>();
static Scanner sc = new Scanner(System.in);
static String userString;
static String latinString;
static String temp;
public static void main(String[] args) {
while (true) {
latinString = "";
System.out.print("Enter a string to be converted into Pig Latin. To stop, enter a blank input: ");
String userString = sc.nextLine();
if (userString.isEmpty()) {
break;
}
ArrayList<String> al = new ArrayList<String>(Arrays.asList(userString.split("\\s")));
for(int i = 0; i <= al.size() - 1; i++) {
temp = al.get(i);
String tester = temp.toUpperCase();
if (tester.charAt(0) == 'A' || tester.charAt(0) == 'E' || tester.charAt(0) == 'I' || tester.charAt(0) == 'O' ||
tester.charAt(0) == 'U' ) {
latinString = latinString + temp + "ay ";
} else {
latinString = latinString + temp.substring(1) + temp.charAt(0) + "ay ";
}
}
System.out.println(latinString);
}
sc.close();
}
}