Advertisement
Go-Ice

Sophomore Java Homework-P5.15 v2

Oct 21st, 2014
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. /**
  2.  * Name: Method practice - String reverse (recursive method)
  3.  * @author LinChuWen
  4.  * Date: 2014.10.22
  5.  *
  6.  * NCHU EE,course number:2335
  7.  * course name: Object Oriented Language
  8.  * Textbook: Big Java:Late Objects-Cay S. Horstmann
  9.  * Problem: P5.15
  10.  * Description: Input a string, reverse it, print out the result.
  11.  */
  12. import java.util.*;
  13. public class HW4_P5_15_v2 {
  14.    
  15.     private static int counter=0;
  16.    
  17.     public static void main(String[] args) {
  18.         Scanner input = new Scanner(System.in);
  19.         System.out.print("Please input a string: ");
  20.  
  21.         while(input.hasNext()){
  22.             String str_input = input.nextLine();
  23.             System.out.printf("reverse result: %s\n\n", reverse(str_input));
  24.             System.out.print("Please input a string: ");
  25.             counter=0;
  26.         } //while end
  27.        
  28.         input.close();
  29.     } //main end
  30.    
  31.     public static String reverse( String str ){
  32.         counter++;
  33.        
  34.         if(counter<str.length()-counter+1){
  35.             str = str + str.charAt(str.length()-2*counter);
  36.             return reverse(str);   
  37.         } //if end
  38.         else
  39.             return str.substring(counter-1, str.length());
  40.        
  41.     } //reverse() end
  42.    
  43. } //class end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement