学习java,找不到符号
我正在学习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
一些一般的“良好编码”建议:
- 类名应该代表’thing’,通常classname是名词(例如“StringTool”)
- 方法应该代表一个动作,通常一个方法名是一个动词(例如“反向”)
- 参数和变量名称应该是有意义的并描述它们代表的内容。
- 您不应该重新分配方法参数,因为它可能会产生误导。
- 一个方法应该只有一个责任(所以不要反转AND打印一个字符串)。 这促进了清晰度和重用。
我已将这些建议应用于您已完成的代码,请参阅以下内容:
public class StringTool { public static String reverse(String source) { // stop condition of the recursion if (source.isEmpty()) { return ""; } int lastPosition = source.length() - 1; String lastCharacter = source.charAt(lastPosition); String restOfSource = source.substring(0, lastPosition); // place the last character at the beginning and reverse the rest // of the source recursively return lastCharacter + reverse(restOfSource); } // test method public static void main(String args[]) { System.out.println(reverse("A STRING")); } }
在if语句中,您将0分配给s.length而不是检查。 这样做:
if(s.length()==0) //rest of your code
另一个错误是s.charAt(s.length())
。 字符串中第i个字符的索引是(i-1),类似于数组的索引。 所以字符串的最后一个字符有索引(s.length()-1)
。 所以用s.charAt(s.length()-1)
替换那行代码。
这应该更好地反映您要完成的任务:
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); } } public class RTest { public static void main(String args[]) { Back b = new Back(); b.Backwards("RAPE APE"); } }
- length()是一个函数
- 比较使用
==
- 您必须实例化b才能使用它
你忘记了括号:
s.length()
length
是方法 ,而不是属性。 你必须这样使用它:
s.length(); // note the use of parens
此外,由于以下情况,修复后会出现编译错误:
if (s.length = 0) {
它应该是
if (s.length == 0) {
最后,在您的main
方法中,必须使用实例化b
变量
Back b = new Back();
–使用String
我们提供了一个名为length()
的函数,而不是字段length
。
–如果你使用的是Array
那么它就是length
因为Array有一个且只有一个名为length
Instance变量 。
例如:
s.length() == 0;