java - 为什么在使用递归时会收到此错误消息?

标签 java string recursion

当我完成有关在递归循环中反向打印字符串的练习时,我收到此消息:赋值的左侧必须是变量。 我只是想知道是否有人可以提供解释? 错误消息出现在最后一行......我不明白,为什么? 这是我的代码:

import java.util.Scanner;

public class Excersise {

    public static void main(String[] args) {

        // Create a Scanner
        Scanner input = new Scanner(System.in);
        //Prompt the user to enter a string
        System.out.print("Enter a string: ");
        String s = input.nextLine();
        reverseDisplay(s);

    }

    public static void reverseDisplay(String value) {

        //Base case
        if (value.length() < 2) { 
            System.out.println(value);
        } else {
            //Recursion
            reverseDisplay(value.substring(1)) + value.charAt(0); <--error

        }
    }
}

最佳答案

import java.util.Scanner;
public class Exercise {
    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);
        //Prompt the user to enter a string
        System.out.print("Enter a string: ");
        String s = input.nextLine();
        reverseDisplay(s);
        System.out.println();
    }
    public static void reverseDisplay(String value) {
        //Base case
        if (value.length() < 2) { 
            System.out.print(value);
        } else {
            //Recursion
            //calls for string without first char
            reverseDisplay(value.substring(1));
            //prints first char
            System.out.print(value.charAt(0));
        }
    }
}

这有效。您的递归方法是正确的,但您希望在对字符串的其余部分调用该方法后打印第一个字符。我还在 main 的末尾添加了另一个 println ,这样反转的字符串就会出现在它自己的行上。
您得到的编译器错误是因为编译器认为该行应该是一个赋值(如 int a = b + c )并且没有看到 =。

关于java - 为什么在使用递归时会收到此错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21817301/

相关文章:

python - 递归函数-Collat​​z

java - OpenGL初始化方法

java - 使用struts2标签测试字符串长度

java - 用户支持的分配未满足跨步要求,退回到单独分配

python - 使用 Python 查找盘符 (Windows)

java - String.Split 的行为不符合预期

java - Tomcat 为每个 HTTP 请求分配一个新线程,那么使用 future.get() 的动机是什么?

比较两个字符串并删除相同的字母

SQL递归逻辑

java - 递归Java,检查节点之间的冲突