I'm learning Java and stuck on a self test exercise writing a recursive function that prints a string backwards...
I understand the compiler error but I'm not sure what to do about it.
My code...
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");
}
}
Compiler output...
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
Finished code...
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");
}
}
List class without declaring the corresponding import, therefore the cannot find symbol error occurs. Adding the missing import statement (line 4 in Fig. 4(b)) solves the problem.
It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.
* Option A, placing a semicolon at the end of the first line of an IF statement is not a compilation error so it is correct.
Write it like this:
s.length() == 0 // it's a method, not an attribute
Some general 'good coding' suggestions:
I have applied these suggestions to your finished code, see below:
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With