我编写了一个递归代码,但我不知道为什么它不能工作。(我更改了前面的一些错误,但它仍然不能工作:( )
问题是:
编写一个递归方法
doubleReverse("hello")打印oolllleehh
到目前为止,我所掌握的代码如下:
public class Recursion{
    public static void main(String[] args) {
        String s = "hello"; 
        doubleReverse(s); 
    }
    public static void doubleReverse(String s) {
        if (s == null || s.equals("")){
        return; 
    }
    System.out.print(s.charAt(s.length()-1) + s.charAt(s.length()-1) + doubleReverse(s.substring(1)));  
    }
}期望输出的doubleReverse("hello")打印oolllleehh
我得到的输出是:不编译
错误消息:
发现2个错误:
File: /Users/jaeahn/Desktop/CSCI /Practice/Recursion.java  [line: 12]
Error: /Users/jaeahn/Desktop/CSCI /Practice/Recursion.java:12: reference to print is ambiguous, both method print(char[]) in java.io.PrintStream and method print(java.lang.String) in java.io.PrintStream match
File: /Users/jaeahn/Desktop/CSCI /Practice/Recursion.java  [line: 12]
Error: /Users/jaeahn/Desktop/CSCI /Practice/Recursion.java:12: 'void' type not allowed here发布于 2015-07-12 01:50:34
您不需要返回任何内容,但每次都需要传递一个较小的字符串版本,直到打印完所有字符为止。这里有一个实现..。
public static void recurse(String str){
    if(str.length() > 0) {
        System.out.print(str.charAt(str.length()-1));
        System.out.print(str.charAt(str.length()-1));
        recurse(str.substring(0, str.length() - 1));
    }
}发布于 2015-07-12 01:51:18
您的程序有错误,因为void方法返回一个对象"null":
public static void doubleReverse(String s) {    // <-- void method.
    if (s == null || s.equals("")) {
        return;                                 // <-- return object "null".
    }
}在这种情况下,您不需要递归。
public class Solution {
    public static String reverseWords(String sentence) {
        String[] parts = sentence.split("");
        StringBuilder builder = new StringBuilder();
        builder.append(parts[parts.length - 1]).append(parts[parts.length - 1]);
        for (int i = parts.length - 2; i >= 0; --i) {
            builder.append("").append(parts[i]).append(parts[i]);
        }
        return builder.toString();
    }
    public static void main(String[] args) {
        System.out.println(reverseWords("hello"));
    }
}
//  Result:
//  oolllleehh如果您想使用递归
public class Solution {
    public static String reverse(String str) {
        String reverse = "";
        if (str.length() == 1) {
            return (str + str);
        } else {
            reverse += str.charAt(str.length() - 1);
            reverse += str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));            
            return reverse;
        }
    }
    public static void main(String[] args) {
        System.out.println(reverse("hello"));
    }
}
//  Result:
//  oolllleehhhttps://stackoverflow.com/questions/31363529
复制相似问题