Advertisement
KuoHsiangYu

Java遞迴程式1.java

Sep 4th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. /*
  2. Java遞迴程式1.java
  3. author:郭翔宇
  4. 參考上述程式碼改寫完成使用Java語言利用遞迴函數進行正向輸入逆向輸出。
  5. 輸入(input):12345
  6. 輸出(output):54321
  7. */
  8. package com.sample;
  9.  
  10. import java.util.Scanner;
  11.  
  12. public class Project26 {
  13.    
  14.     public static void main(String[] args) {
  15.         // TODO code application logic here
  16.         Scanner scanner = new Scanner(System.in);
  17.         String s1 = "";
  18.         System.out.printf("input : ");
  19.         s1 = scanner.next();
  20.  
  21.         // 方法1
  22.         char[] c1 = new char[s1.length()];
  23.         for (int i = 0; i < s1.length(); i++) {
  24.             c1[i] = s1.charAt(i);
  25.         }
  26.         System.out.printf("output : ");
  27.         reverseSentence(c1, 0);
  28.         System.out.printf("\n");
  29.  
  30.         // 方法2
  31.         // System.out.printf("output : ");
  32.         // reverseSentence(s1.toCharArray(), 0);
  33.         // System.out.printf("\n");
  34.     }
  35.  
  36.     private static void reverseSentence(char[] c1, int i) {
  37.         // throw new UnsupportedOperationException("Not supported yet.");
  38.         // To change body of generated methods, choose Tools | Templates.
  39.         if (i < c1.length) {
  40.             // System.out.print(c1[i]);//正向輸出
  41.             reverseSentence(c1, i + 1);
  42.             System.out.print(c1[i]);// 逆向輸出
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement