import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String[] words = input.split(" ");
StringBuilder pigLatin = new StringBuilder();
for (String word : words) {
if (word.isEmpty()) {
pigLatin.append(" ");
continue;
}
String firstLetter = word.substring(0, 1);
String remainingLetters = word.substring(1);
if (isVowel(firstLetter)) {
pigLatin.append(word).append("way ");
} else {
pigLatin.append(remainingLetters).append(firstLetter).append("ay ");
}
}
System.out.println("Pig Latin: " + pigLatin.toString().trim());
}
private static boolean isVowel(String letter) {
return letter.equalsIgnoreCase("a") ||
letter.equalsIgnoreCase("e") ||
letter.equalsIgnoreCase("i") ||
letter.equalsIgnoreCase("o") ||
letter.equalsIgnoreCase("u");
}
}
```
Explanation:
1. Import Scanner: This line imports the `Scanner` class for reading user input.
2. Create Scanner Object: A `Scanner` object is created to read input from the console.
3. Prompt for Input: The program prompts the user to enter a string.
4. Read Input: The user's input is read using `scanner.nextLine()` and stored in the `input` variable.
5. Split String into Words: The `input` string is split into individual words using `input.split(" ")` and stored in the `words` array.
6. Iterate through Words: The program iterates through each word in the `words` array.
7. Handle Empty Words: If a word is empty, a space is added to the `pigLatin` StringBuilder.
8. Extract First Letter and Remaining Letters: For each non-empty word, the first letter is extracted using `word.substring(0, 1)` and the remaining letters using `word.substring(1)`.
9. Check for Vowel: The `isVowel()` method is called to check if the first letter is a vowel.
10. Pig Latin Conversion:
- If the first letter is a vowel, the word is appended with "way".
- If the first letter is a consonant, the remaining letters are appended followed by the first letter and "ay".
11. Append to Pig Latin: The converted word is appended to the `pigLatin` StringBuilder with a space.
12. Print Pig Latin: The final `pigLatin` string, trimmed of any trailing spaces, is printed to the console.
13. isVowel() Method: This method checks if a given letter is a vowel (case-insensitive).
How to run this program:
1. Save the code as a Java file (e.g., `PigLatin.java`).
2. Compile the code using a Java compiler (e.g., `javac PigLatin.java`).
3. Run the program using the command `java PigLatin`.
4. Enter a string when prompted, and the program will output the Pig Latin translation.