Pig Latin翻译器Java代码故障排查及优化求助
Fixing and Optimizing Your Pig Latin Translator
Hey there! Let's work through fixing your Pig Latin translator and cleaning up those messy index/substring operations. First, let's break down the issues in your current code, then share a revised, cleaner version.
Issues in the Original Code
- Empty String Crash: If your input has multiple spaces (e.g., "Hello world"), your word-splitting logic will eventually pass an empty string to the
translatormethod. Callinginput.charAt(0)on an empty string throws aStringIndexOutOfBoundsException. - Clunky Vowel Checks: Repeating
input.charAt(index) == 'A' || ...multiple times makes the code hard to read and maintain. - Error-Prone Word Splitting: Manually handling
indexOf(" ")and substring operations is fragile, especially with edge cases like trailing spaces or consecutive spaces. - Odd All-Consonant Word Output: Words with no vowels (like "MYTH") will result in a translation starting with a hyphen (e.g., "-MYTHay ") which isn't ideal.
Fixed & Optimized Code
Here's a revised version that addresses these issues and uses more idiomatic, readable Java:
import java.util.Scanner; import static java.lang.System.*; public class PigLatinTranslator { private static final Scanner scan = new Scanner(in); // Centralize vowels for easy checks and future edits private static final String VOWELS = "AEIOU"; public static void main(String args[]) { out.println("Enter the sentence you want to translate"); String input = scan.nextLine().toUpperCase(); // Split into words using one or more spaces as delimiter String[] words = input.split("\\s+"); StringBuilder translated = new StringBuilder(); for (String word : words) { translated.append(translator(word)); } out.println(translated.toString().trim()); // Trim any trailing extra space } public static String translator(String input) { // Guard clause for empty strings (from unexpected splits) if (input.isEmpty()) { return ""; } int firstVowelIndex = findFirstVowelIndex(input); if (firstVowelIndex == 0) { // Word starts with a vowel: append "-ay " return input + "-ay "; } else if (firstVowelIndex == -1) { // No vowels found: adjust rule if needed, default to adding "-ay " return input + "-ay "; } else { // Move leading consonants to end and format String consonants = input.substring(0, firstVowelIndex); String restOfWord = input.substring(firstVowelIndex); return restOfWord + "-" + consonants + "ay "; } } // Helper method to clean up vowel-finding logic private static int findFirstVowelIndex(String word) { for (int i = 0; i < word.length(); i++) { if (VOWELS.indexOf(word.charAt(i)) != -1) { return i; } } return -1; // No vowels detected } }
Key Improvements
- Simpler Word Splitting: Using
split("\\s+")automatically handles multiple spaces and trailing spaces, eliminating the need for manual substring/index work. - Reusable Vowel Check: The
VOWELSstring and dedicated helper method clean up repeated vowel checks, making it easy to adjust rules later (like adding 'Y' as a vowel if needed). - More Efficient String Building:
StringBuilderreplaces repeated+=concatenation, which creates unnecessary string objects and slows down performance for longer sentences. - Clear Edge Case Handling: We explicitly handle empty strings and all-consonant words to avoid crashes and unexpected output.
- Cleaner Separation of Concerns: Breaking vowel-finding into a separate method makes the
translatormethod's purpose immediately clear.
Optional Adjustment
If your Pig Latin rules require different handling for all-consonant words (e.g., adding "-way" instead of "-ay"), just modify the else if (firstVowelIndex == -1) block to match your desired behavior.
内容的提问来源于stack exchange,提问作者mdeligt_
相关产品推荐
相关产品推荐

