[英]Reversing a String Using Recursion
我在這里有點問題。 我正在嘗試使用遞歸來反轉用戶輸入的字符串,但我一直收到錯誤消息。 基本上,應該調用無參數的void遞歸函數以向后打印字符串。 我在第23行的錯誤字下僅出現錯誤,該錯誤指出“類型RecursionReversal的方法reverse()不適用於參數(String)”。 在Eclipse中可以快速修復該問題,但我都不需要這些修復程序。 我想念什么嗎?
import java.util.Scanner;
public class RecursionReversal
{
public static String origChars;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 characters:");
origChars= input.nextLine();
reverse();
}
public static void reverse()
{
if(origChars.length() <= 1)
return;
else
reverse(origChars.substring(1) + origChars.charAt(0));
}
}
向reverse
方法添加參數以對應於在方法內進行的方法調用
public static void reverse(String input)
您的方法應采用String
參數; 使用static
字段可能會起作用,但是有不好的代碼味道。 無論如何,在輸入String
獲取最后一個字符,然后對其他所有內容進行子字符串化。 喜歡,
public static String reverse(String str) {
if (str.length() <= 1)
return str;
else
return Character.toString(str.charAt(str.length() - 1))
+ reverse(str.substring(0, str.length() - 1));
}
如果必須使用全局origChars
來完成,則可以使用類似的方法來完成,但是必須先調用origChars
然后再調用reverse()
(無參數),例如
private static String origChars;
public static void reverse() {
if (origChars.length() <= 1)
System.out.print(origChars);
else {
System.out.print(origChars.charAt(origChars.length() - 1));
origChars = origChars.substring(0, origChars.length() - 1);
reverse();
}
}
您沒有為反向函數定義參數或返回類型。 要使用遞歸,我建議將您的反向方法替換為
public static String reverse(String s)
{
if(s.length() <= 1)
return s;
else
reverse(s.substring(1) + s.charAt(0));
}
你有正確的想法, reverse(s.substring(1) + s.charAt(0));
語句,但您需要返回類型,否則將無法獲得結果。 其次,沒有參數,該方法無法知道String
哪一部分要反轉。
最后,要使其工作,請從您的main
調用origichars = reverse(origChars);
而不是調用reverse();
。
這是使用無參數void函數執行此操作的方法。 reverse()
origChars
第一個char
,調用reverse()
然后將char
放回origChars
。
public static void reverse()
{
if(origChars.length() <= 1)
return;
char first = origChars.charAt(0);
origChars = origChars.substring(1);
reverse();
origChars+=first;
}
嘗試這個:
public String reverseUsingRecursion(String str){
if(str.length() == 0 || str.length() == 1){
return str;
}
String reverseString = reverseUsingRecursion(str.substring(1))
+ str.charAt(0);
return reverseString;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.