In: Computer Science
Please write in Java and have two methods: the main method and the reverse word
Write a method that reads a line and reverses the words in the line (not the characters) using a stack. For example, given the following input:
The quick brown fox jumps over the lazy dog
you should get the following output:
dog lazy the over jumps fox brown quick The
Then create a main method to prompt the user to enter a line of words to be reversed using the previous reverse method.
The required code and corresponding output are as follows. The code is well commented for better understanding.
//Java program to reverse sentence
import java.util.*;
class reverseSentence{
 
// Function to reverse the words
// of the given String
// using stack. 
static void reverseWord(String s)
{
  // Create an empty String stack
  Stack<String> stk = new Stack<String>();
 
  // Create an empty temporary String
  String temp = "";
 
  // Traversing the entire String
  for(int i = 0; i < s.length(); i++)
  {
    if(s.charAt(i) == ' ')
    {
       
      // Push the temporary 
      // variable into the stack
      stk.add(temp); 
       
      // Assigning temporary 
      // variable as empty
      temp = "";          
    }
    else
    {
      temp = temp + s.charAt(i);
    }
 
  }
 
  // For the last word 
  // of the String
  stk.add(temp);
 
  while(!stk.isEmpty()) 
  {
    // Get the words in 
    // reverse order 
    temp = stk.peek();
    System.out.print(temp + " ");
    stk.pop();
  }
   
  System.out.println();
}
 
//Driver code
public static void main(String[] args)
{
  String s;
  Scanner sc = new Scanner(System.in);
  System.out.println("\nEnter a line of words to be reversed:\n");
  s=sc.nextLine();//reads sentence 
  System.out.println("\nThe reversed line is:\n");
  reverseWord(s); //calls function
}
}
 
Output:
