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