我写了一个递归代码,但不知道为什么不行。(我改了一些之前的错误,但还是不行:( )
问题是:
编写一个递归方法
a.将字符串的每个字符反转两次 b. 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
最佳答案
您不需要返回任何内容,但每次都需要传递较小版本的字符串,直到打印完所有字符为止。这是一种实现...
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));
}
}
关于java - 简单的递归代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363529/