Reverse a String , Code was not working properly

I think theres something wrong with my syntax. So please help me with those syntax:

public class Main { 

  public static void main(String arg[]) { 
    String number = "1234";
    System.out.println("original String: " + number);
    String reversed = inPlaceReverse(number);
    System.out.println("reversed String: " + reversed); 
  } 

  public  String inPlaceReverse(final String input) {
    final StringBuilder builder = new StringBuilder(input); 
    int length = builder.length();
    for (int i = 0; i < length / 2; i++) { 
      final char current = builder.charAt(i);
      final int otherEnd = length - i - 1;
      builder.setCharAt(i, .charAt(otherEnd)); // swap 
      builder.setCharAt(otherEnd, current); 
    }
    return builder.toString(); 
  }

}  

Reverse function is not working properly.

Answer

There were some errors in your code.

1) error: illegal start of expression builder.setCharAt(i, .charAt(otherEnd));

correction: builder.setCharAt(i, **builder**.charAt(otherEnd));

2) error: non-static method inPlaceReverse(String) cannot be referenced from a static context

This is because you have declared main() as static whereas your isPlaceReverse() is non-static. You cannot reference a non-static member within a static member.

Change your function definition to public **static** String inPlaceReverse(final String input)

After you make the above corrections, you’ll get the desired output:

public class Main {

    public static void main(String args[]) {

        String number = "1234";
        System.out.println("original String: " + number);
        String reversed = inPlaceReverse(number);
        System.out.println("reversed String: " + reversed);
    }


    public static String inPlaceReverse(final String input) {
        final StringBuilder builder = new StringBuilder(input);
        int length = builder.length();
        for (int i = 0; i < length / 2; i++) {
            final char current = builder.charAt(i);
            final int otherEnd = length - i - 1;
            builder.setCharAt(i, builder.charAt(otherEnd)); // swap
            builder.setCharAt(otherEnd, current);
        }

        return builder.toString();
    }
}

Output original String: 1234 reversed String: 4321

Leave a Reply

Your email address will not be published. Required fields are marked *