我正在学习Java并坚持进行自我测试练习,编写了一个向后打印字符串的递归函数...
我了解编译器错误,但不确定如何处理。
我的代码...
class Back {
void Backwards(String s) {
if (s.length = 0) {
System.out.println();
return;
}
System.out.print(s.charAt(s.length));
s = s.substring(0, s.length-1);
Backwards(s);
}
}
class RTest {
public static void main(String args[]) {
Back b;
b.Backwards("A STRING");
}
}
编译器输出...
john@fekete:~/javadev$ javac Recur.java
Recur.java:3: error: cannot find symbol
if (s.length = 0) {
^
symbol: variable length
location: variable s of type String
Recur.java:7: error: cannot find symbol
System.out.print(s.charAt(s.length));
^
symbol: variable length
location: variable s of type String
Recur.java:8: error: cannot find symbol
s = s.substring(0, s.length-1);
^
symbol: variable length
location: variable s of type String
3 errors
完成的代码...
class Back {
static void backwards(String s) {
if (s.length() == 0) {
System.out.println();
return;
}
System.out.print(s.charAt(s.length()-1));
s = s.substring(0, s.length()-1);
backwards(s);
}
}
class RTest {
public static void main(String args[]) {
Back.backwards("A STRING");
}
}
最佳答案
像这样写:
s.length() == 0 // it's a method, not an attribute