使用遞迴反轉句子 Java 程式


在本文中,我們將瞭解如何使用遞迴反轉句子。遞迴函式是指多次呼叫自身直到滿足特定條件的函式。

遞迴函式是指多次呼叫自身直到滿足特定條件的函式。

遞迴是重複以自相似方式出現的專案的過程。在程式語言中,如果一個程式允許你在同一個函式內部呼叫一個函式,那麼它被稱為該函式的遞迴呼叫。

許多程式語言透過棧來實現遞迴。通常,每當一個函式(呼叫方)呼叫另一個函式(被呼叫方)或自身作為被呼叫方時,呼叫方函式都會將執行控制權轉移到被呼叫方。此轉移過程可能還涉及將某些資料從呼叫方傳遞到被呼叫方。

以下是相同內容的演示 -

輸入

假設我們的輸入是 -

Enter the sentence : Have a nice evening

輸出

期望的輸出將是 -

The reversed input is: gnineve ecin a evaH

演算法

Step 1 - START
Step 2 - Declare two string values namely my_input and my_result
Step 3 - Read the required values from the user/ define the values
Step 4 - A recursive function ‘reverseString is defined which takes an string as input and returns the character at the last position.
Step 5 - The function is called recursively until the value of ‘my_input’ is not an empty string.
Step 6 - The recursive function is called and the value ‘my_input’ is passed to it. Store the return value
Step 7 - Display the result
Step 8 - Stop

示例 1

這裡,輸入是由使用者根據提示輸入的。您可以在我們的編碼環境工具 執行按鈕中即時嘗試此示例。

import java.util.Scanner;
public class Reverse {
   public static void main(String[] args) {
      String my_input, my_result;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the sentence : ");
      my_input = my_scanner.nextLine();
      my_result = reverseString(my_input);
      System.out.println("The reversed input is: " + my_result);
   }
   public static String reverseString(String my_input) {
      if (my_input.isEmpty())
        return my_input;
      return reverseString(my_input.substring(1)) + my_input.charAt(0);
   }
}

輸出

Required packages have been imported
A reader object has been defined
Enter the sentence : Have a nice evening
The reversed input is: gnineve ecin a evaH

示例 2

這裡,整數已預先定義,並訪問其值並在控制檯上顯示。

public class Reverse {
   public static void main(String[] args) {
      String my_input, my_result;
      my_input = "Have a nice evening";
      System.out.println("The string is defined as :" +my_input);
      my_result = reverseString(my_input);
      System.out.println("The reversed input is: " + my_result);
   }
   public static String reverseString(String my_input) {
      if (my_input.isEmpty())
         return my_input;
      return reverseString(my_input.substring(1)) + my_input.charAt(0);
   }
}

輸出

The string is defined as :Have a nice evening
The reversed input is: gnineve ecin a evaH

更新於: 2022年2月22日

318 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.