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

如何用Java打印字符串中首尾字符相同的所有单词?

Fixing Your Java Code to Capture All Matching Words

Looks like your code is missing the last word (MODEM) because it only processes words when it encounters a space, plus there are a few other issues preventing proper execution. Let's break down what's wrong and fix it:

Key Issues in the Original Code

  • Invalid main method: Java requires the program entry point to be public static void main(String[] args) — your current void main() won't work as the starting point for your program.
  • Last word is ignored: Your code only checks a word when it hits a space. Since "MODEM" is the final word with no trailing space, it never gets evaluated.
  • Incorrect word reset: After processing a word, you set w=" " instead of clearing it to an empty string "", which would mess up building subsequent words.
  • Premature printing: You print the result every time you hit a space, leading to partial, messy outputs instead of a clean list of all matching words.
  • Redundant code: The line n=n+""; does nothing and can be removed entirely.

Fixed & Improved Code

import java.util.Scanner;

class Word {
    public static void main(String[] args) {
        char currentChar;
        String currentWord = "";
        String matchingWords = "";
        
        Scanner inputScanner = new Scanner(System.in);
        System.out.println("Enter a String");
        String inputString = inputScanner.nextLine();
        
        // Loop through each character in the input string
        for (int i = 0; i < inputString.length(); i++) {
            currentChar = inputString.charAt(i);
            
            // Build the current word if we're not at a space
            if (currentChar != ' ') {
                currentWord += currentChar;
            } else {
                // Check if the current word qualifies and add it to results
                matchingWords = addMatchingWord(currentWord, matchingWords);
                currentWord = ""; // Reset for the next word
            }
        }
        
        // Critical: Check the last word (no trailing space to trigger the else block)
        matchingWords = addMatchingWord(currentWord, matchingWords);
        
        // Print the final results
        if (!matchingWords.isEmpty()) {
            System.out.println("Words with matching first and last characters: " + matchingWords);
        } else {
            System.out.println("No words found with matching first and last characters.");
        }
        
        inputScanner.close();
    }
    
    // Helper method to check a word and add it to the result string
    private static String addMatchingWord(String word, String result) {
        // Skip empty strings (in case of multiple spaces)
        if (word.length() >= 1) {
            char firstChar = word.charAt(0);
            char lastChar = word.charAt(word.length() - 1);
            
            if (firstChar == lastChar) {
                // Add a space separator if we already have results
                if (!result.isEmpty()) {
                    result += " ";
                }
                result += word;
            }
        }
        return result;
    }
}

What Changed & Why

  1. Proper main method: Now follows Java's required entry point structure so your program can run correctly.
  2. Handles the final word: After the loop finishes, we explicitly check the last word that wasn't followed by a space — this fixes the MODEM missing issue.
  3. Clean word reset: currentWord is reset to an empty string after processing each word, ensuring we start fresh for the next word.
  4. Helper method: Extracts the word-checking logic into a separate method for better readability and reusability.
  5. Clean output: Collects all matching words first, then prints them once with proper spacing. We also handle cases where no matching words exist to avoid empty outputs.

When you test this code with input "MADAM HAVE A MODEM", you'll get the expected output:

Words with matching first and last characters: MADAM MODEM

内容的提问来源于stack exchange,提问作者Subhradeep Basu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:39:20