Java实现PigLatin转换仅输出首个单词,求代码修正方案
Fixing Your Pig Latin Conversion Code
Let's work through the issues in your code and get it to convert all words correctly. The main problems are an invalid entry point method, logic that only handles the first word, and messy string manipulation that breaks subsequent processing.
Key Issues in Your Original Code
- Incorrect Main Method: Java requires the program entry point to be
public static void main(String[] args)— your method signature doesn't match this, so the JVM can't properly run your code. - Single-Word Processing: The code that finds vowels and builds the Pig Latin word only runs when
i==0, so it never touches the other words in your input. - Buggy String Handling: Resetting
i=0after cutting the string leads to inconsistent loop behavior, and your word-count logic doesn't properly drive processing for all words.
Fixed Code
Here's a cleaned-up, working version that handles all words as expected:
public class PigLatin { public static void main(String[] args) { // Target input: "Her food is stolen" String input = "Her food is stolen"; input = input.toUpperCase(); String[] words = input.split(" "); // Split input into individual words StringBuilder result = new StringBuilder(); for (String word : words) { int firstVowelIndex = findFirstVowel(word); String pigLatinWord; if (firstVowelIndex == 0) { // Word starts with a vowel, just append "AY" pigLatinWord = word + "AY"; } else { // Move consonants before first vowel to the end, then add "AY" pigLatinWord = word.substring(firstVowelIndex) + word.substring(0, firstVowelIndex) + "AY"; } result.append(pigLatinWord).append(" "); } // Print the final result (trim removes the trailing space) System.out.println(result.toString().trim()); } // Helper method to locate the first vowel in a word private static int findFirstVowel(String word) { for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') { return i; } } // Edge case: no vowels found (treat as starting with vowel) return 0; } }
What's Improved
- Valid Entry Point: Uses the standard Java main method signature so your program runs correctly.
- Word-by-Word Processing: Splitting the input into an array of words makes it simple to iterate over each one without messy string cuts.
- Reusable Logic: The
findFirstVowelhelper method cleans up the code and makes it easier to maintain or modify later. - Efficient Result Building: Using
StringBuilderavoids repeated print calls and builds the final output cleanly.
When you run this code with your target input, it will output:
ERHAY OODFAY ISAY OLENSTAY
内容的提问来源于stack exchange,提问作者Tejasvini Goel
相关产品推荐
相关产品推荐

