javaarraysregexswapstringbuilder

Swap the first and the last words and reverse all the middle characters


Description

Guru gave a task to his students.   He gave a sentence,  and the students have to swap the first and the last words and reverse all the characters between those words.   Help the students to solve this task using a java program.

Requirements:

Note:

Please do not use System.exit(0) to terminate the program.

Example input/output examples.  All input is preceded by the prompt Enter the sentence

Example 1:

Input: Do you wear your mask
Output: mask ruoy raew uoy Do

Example 2:

Input: Card reader
Output: Invalid Length

Example 3:

Input: Refer @ friend
Output: Refer @ friend is an invalid sentence

import java.util.Scanner;

class SentenceProcessor {
    
    // Method to check if the sentence is valid
    public boolean isValidSentence(String sentence) {
        return sentence.matches("[a-zA-Z ]+"); // Only alphabets and spaces allowed
    }

    // Method to process the sentence
    public String processSentence(String sentence) {
        if (!isValidSentence(sentence)) {
            return sentence + " is an invalid sentence";
        }

        String[] words = sentence.trim().split("\\s+"); // Split by whitespace

        if (words.length <= 2) {
            return "Invalid Length";
        }

        // Swap first and last words
        String firstWord = words[0];
        String lastWord = words[words.length - 1];
        words[0] = lastWord;
        words[words.length - 1] = firstWord;

        // Reverse middle words
        for (int i = 1; i < words.length - 1; i++) {
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }

        return String.join(" ", words); // Join words with a space
    }
}

public class UserInterface {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter the sentence");
        String input = sc.nextLine();
        
        SentenceProcessor processor = new SentenceProcessor();
        String result = processor.processSentence(input);
        
        System.out.println(result);
        
        sc.close(); // Close the scanner to avoid resource leaks
    }
}

Output:-

Enter the sentence<br>
Do you wear your mask<br>
mask uoy raew ruoy Do<br>

Expected output:-

Enter the sentence<br>
Do you wear your mask<br>
mask ruoy raew uoy Do<br>

Tried resolving this but I am failing to get desired output. I also tried using various open sources which were not able to give me correct code. They are repetitively giving me same output(like chatgpt, copilot).


Solution

  • I originally thought your requirements didn't match one of your expected outputs. I was corrected in the comments.

    This method reverses the order of the words in an array and then reverses each word, excluding the first and last words.

    // Method to process the sentence
    static public String processSentence(String sentence) {
        if (!isValidSentence(sentence)) {
            return sentence + " is an invalid sentence";
        }
    
        String[] words = sentence.trim().split("\\s+"); // Split by whitespace
    
        if (words.length <= 2) {
            return "Invalid Length";
        }
    
        //Swap all words
        String[] reverseWords = new String[words.length];
        for(int i = words.length - 1; i >= 0; i--)
        {
            reverseWords[(reverseWords.length - 1) - i] = words[i];
        }
    
        // Reverse middle words
        for (int i = 1; i < words.length - 1; i++) {
            reverseWords[i] = new StringBuilder(reverseWords[i]).reverse().toString();
        }
    
        return String.join(" ", reverseWords); // Join words with a space
    }
    

    Output:

    Do you wear your mask
    mask ruoy raew uoy Do