Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.Scanner;
  5.  
  6. public class cs491f14_01_reverse_words  {
  7.  
  8.     public static void main(String args[]) {
  9.         Scanner sc = new Scanner(System.in);
  10.         while (sc.hasNextLine()) {
  11.             String phrase = sc.nextLine();
  12.             reversewords(phrase);
  13.         }
  14.  
  15.     }
  16.    
  17.     public static void reversewords(String phrase) {
  18.             ArrayList<String> list = new ArrayList<String>();
  19.            
  20.             // Remove the .
  21.             String lastchar = String.valueOf(phrase.charAt(phrase.length()-1));
  22.            
  23.            
  24.             phrase = phrase.replace(lastchar , "");
  25.            
  26.             // Split into Words
  27.             String split[] = phrase.split(" ");
  28.            
  29.             // 1) Push Words Onto List.
  30.             for (String word : split )  {
  31.                 list.add(word);
  32.             }
  33.        
  34.             // Reverse words in list.
  35.             Collections.reverse(list);
  36.    
  37.             // Go through the list and adjust commas if necessary..
  38.             for (int i = 0; i < list.size() ; i++ ) {
  39.                 if ( list.get(i).contains(",") ) {
  40.                     // Add ',' to previous word
  41.                     list.set( i-1 , list.get(i-1 ) + ",");
  42.                    
  43.                     // remove ',' from current word
  44.                     list.set( i , list.get(i).replace("," , ""));
  45.                
  46.                 }
  47.                
  48.             }
  49.            
  50.             // You Really want to use String builder?  Ok..
  51.             StringBuilder sB = new StringBuilder("");
  52.             for( String v : list ) {
  53.                 sB.append(v + " ");
  54.             }
  55.            
  56.             // Replace the last space the last space with a period.
  57.             sB.replace(sB.length()-1, sB.length()-1, lastchar);
  58.             System.out.println(sB.toString().trim());
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement