Derrik Antrium Derrik Antrium - 3 months ago 15
Java Question

How to write a Java method reverse (String s) in a class that returns a string consisting of characters in s in reverse order?

I need to write a Java method named reverse(String s) for a StringFunctions class that returns a string consisting of the characters in s in reverse order. So for example, I need to reverse the order of the alphabet.

This is my first attempt:

public class StringFunctions {

public String rev(String s) {
StringBuilder rev = new StringBuilder("abc");
}
public static void main(String[] args) {
System.out.println("string = " + rev.reverse());
}
}


However, I get an error saying: StringFunctions.java:7: error: cannot find symbol
System.out.println("string = " + rev.reverse());

Answer

In java you can not access non static methods or non static fields from static block. main method is static, (see its signature).

You have two choices :

  1. You can make your public String rev(String s) or
  2. You need to create the Object of StringFunctions using new operator and then invoke rev on the created object.

Also although above will resolve your issue But I suggest you write your code like below.

public class StringFunctions {
    public static String rev(String s) {
        StringBuilder rev = new StringBuilder(s); 
        return rev.reverse().toString(); // you process the input and give the output
    }

    public static void main(String[] args) {
        System.out.println(rev("abc")); // you pass your string here
    }
}

In the method 'rev' above I have used Method from StringBuilder although you can implement your own logic also. There are many places on internet where you can learn as how to do this. You can also refer to http://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/ for reference to as how to reverse an array.