Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • The words present in the sentence must be more than 2, else print "Invalid Length"

  • The word should contain only alphabets and space, else print " is an invalid sentence"

Note:

  • In the Sample Input / Output provided,  the highlighted text in bold corresponds to the input given by the user,  and the rest of the text represents the output.

  • Ensure to follow the object-oriented specifications provided in the question description.

  • Ensure to provide the names for classes,  attributes,  and methods as specified in the question description.

  • Adhere to the code template,  if provided

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).

like image 514
MARTIN Avatar asked Oct 23 '25 15:10

MARTIN


2 Answers

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
like image 161
Sedrick Avatar answered Oct 25 '25 05:10

Sedrick


The error is here:

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

the problem is that you invert the order of the letters of the central words, but not the order of them, we can do it this way:

String out = lastWord + " ";
for( int i = words.length - 2; i >= 1; i -- ) {
   out += new StringBuilder( words[ i ] ).reverse().toString() + " ";
}
return out + firstWord;
like image 45
Marce Puente Avatar answered Oct 25 '25 06:10

Marce Puente



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!