fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone {
  9. public static void main (String[] args) throws java.lang.Exception {
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Please Enter a string: ");
  12.  
  13. // split input string in to words by space
  14. String[] words = in.nextLine().split(" ");
  15.  
  16. // performing reverse operation if 3 words are in the input at minimum
  17. // else output is same as input
  18. if (words.length >= 3) {
  19. String rev1 = reverse(words[0]); // reverse word-1
  20. String rev3 = reverse(words[2]); // reverse word-3
  21. // swap word 1 and 3
  22. words[0] = rev3;
  23. words[2] = rev1;
  24. }
  25.  
  26. System.out.println("Reverse: " + String.join(" ", words));
  27. }
  28.  
  29. public static String reverse(String word) {
  30. if (word == null) {
  31. return word;
  32. }
  33. Stack<Character> stack = new Stack<>();
  34. for(int i = 0; i < word.length(); i++){
  35. stack.push(word.charAt(i));
  36. }
  37. StringBuilder sb = new StringBuilder();
  38. while(!stack.empty()){
  39. sb.append(stack.pop());
  40. }
  41. return sb.toString();
  42. }
  43. }
Success #stdin #stdout 0.15s 37952KB
stdin
This is the new normal
stdout
Please Enter a string: 
Reverse: eht is sihT new normal