Friday, March 20, 2009

Exercise 1 --- Word Reverser

/* Programmer: Maribelle Lacno
  * Program name: reverseSent
  * Subject: IT134_Computer Programming 3 
  * Instructor: Mr. Dony Dongiapon 
  * Date Started: 03/16/09 
  * Date Finished: 03/18/09 
  * Purpose: To create a program that reads in a sentence 
  *     from the user and prints it with each word reversed. 
*/

import java.util.*;
public class reverseSent {
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    //ask the user to input data.
    System.out.print("\nInput: ");
    //get the data and store it in variable data.
    String data = scan.nextLine();
    //use StringTokenizer to separate each word.
    StringTokenizer tokens = new StringTokenizer(data);
    while(tokens.hasMoreTokens()){
      String element = tokens.nextToken();
      StringBuffer buffer = new StringBuffer(element);
      //method reverse reverses the contents of the StringBuffer.
      element = buffer.reverse().toString();
      //print the reverse word of data input by user.
      System.out.print(element+" ");
    }
  }
}

No comments:

Post a Comment