You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Pig Latin翻译程序修改求助:函数化翻译+循环终止修复

Fixing Your Pig Latin Java Program (Loop Termination + Encapsulation)

Hey there! Let's get your Pig Latin program working smoothly. I'll walk through fixing the stubborn loop issue, wrapping up the translation logic into a clean function, and making sure the try-catch block does its job properly.

First, Let's Break Down the Issues in Your Current Code

  • Loop Termination Problem: Your do-while condition checks if yourSentence equals "quit", but you're asking users to enter "Yes" or "no" to continue. These two don't line up, so typing "no" never triggers the loop to stop.
  • Unencapsulated Translation Logic: The word translation code is directly stuffed into the main loop, making it hard to reuse or tweak later.
  • Mixed Input Classes: Using both Scanner and TextIO can cause input buffer conflicts, leading to weird behavior when reading the "play again" response.

Modified Working Code

package midtermPigLatin;
import java.util.Scanner;
import java.util.InputMismatchException;

public class midtermPigLatin {

    // Encapsulated translation function: takes a word, returns its Pig Latin version
    public static String translateToPigLatin(String word) {
        // Convert to lowercase once for consistent checks (handles uppercase inputs like "Apple")
        String lowerWord = word.toLowerCase();
        
        if (lowerWord.startsWith("a") || lowerWord.startsWith("e") || 
            lowerWord.startsWith("i") || lowerWord.startsWith("o") || 
            lowerWord.startsWith("u")) {
            return word + "way";
        } else if (lowerWord.startsWith("sh") || lowerWord.startsWith("ch") || 
                   lowerWord.startsWith("th")) {
            return word.substring(2) + word.substring(0, 2) + "ay";
        } else {
            return word.substring(1) + word.substring(0, 1) + "ay";
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean again = true;

        try {
            do {
                System.out.print("Enter your words here: ");
                String yourSentence = input.nextLine();
                
                // Split the input sentence into individual words
                String[] words = yourSentence.split(" ");
                
                // Translate each word and print the result
                for (String word : words) {
                    System.out.print(translateToPigLatin(word) + " ");
                }
                System.out.println();

                // Ask user if they want to keep playing
                System.out.println("Do you want to play again? (Yes/no)");
                String response = input.nextLine().trim().toLowerCase();
                
                // Update loop condition based on user's response
                again = response.equals("yes") || response.equals("y");

            } while (again); // Only loop if the user wants to continue

        } catch (InputMismatchException e) {
            System.out.println("Error: Invalid input type. Please enter text as requested.");
        } catch (Exception e) {
            System.out.println("Unexpected error occurred: " + e.getMessage());
        } finally {
            input.close(); // Clean up the scanner resource when done
        }

        System.out.println("Thanks for playing!");
    }
}

Key Changes Explained

  • Encapsulated Translation: The translateToPigLatin function handles all word-to-Pig-Latin logic. It converts the word to lowercase first, so it works seamlessly with uppercase inputs (like "Apple" instead of just "apple").
  • Fixed Loop Termination: The loop now relies on the again variable, which is set based on the user's "Yes/no" response. We trim and lowercase the response to handle variations like "YES", "No", or even " y ".
  • Unified Input Handling: We removed TextIO and stick with Scanner exclusively to avoid input buffer conflicts. The finally block ensures the scanner is closed properly to prevent resource leaks.
  • Improved Exception Handling: We catch specific exceptions first (like InputMismatchException) for targeted error messages, then catch general exceptions as a fallback for unexpected issues.

内容的提问来源于stack exchange,提问作者Brittany Gradford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:19:16