a problem with the reverse method

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • analoveu
    New Member
    • Jan 2007
    • 36

    a problem with the reverse method

    I have a problem with using the reverse method
    any one give me an exmample or correct my error inside this code

    Code:
    String p="";
    for(int x=0 ; x<=3 ; x++)
       p+=x;
    System.out.print(p);
    String r=reverse(p);
    System.out.print(r);
    but there is an error at the fifth line
    I want to know how to uese the reverse method and print the reversed string

    thank u
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by analoveu
    I have a problem with using the reverse method
    any one give me an exmample or correct my error inside this code

    Code:
    String p="";
    for(int x=0 ; x<=3 ; x++)
    p+=x;
    System.out.print(p);
    String r=reverse(p);
    System.out.print(r);
    but there is an error at the fifth line
    I want to know how to uese the reverse method and print the reversed string

    thank u
    What is the error? Have you written the reverse method? There is no reverse method in the String class. You have to write your own.

    Comment

    • dmjpro
      Top Contributor
      • Jan 2007
      • 2476

      #3
      make sure that what version of j2se u using
      the reverse method supported by j2se 1.5
      ur user defined code will be like this ....

      String reverse(String str)
      {
      String reverse_str;
      char [] char_array = str.toCharArray ();
      char [] char_array1 = new char[str.length()];
      int j = 0;
      for(int i=str.length()-1;i>=0;i++)
      char_array1[j++] = char_array[i];
      return reverse_str = new String(char_arr ay1);
      }

      try this code ...then reply me....
      if don't want to use my user defined code then u can use StringBuffer class
      for details plz link to ..........http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.ht ml
      thankssssssssss s.............

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        Originally posted by analoveu
        I have a problem with using the reverse method
        any one give me an exmample or correct my error inside this code

        Code:
        String p="";
        for(int x=0 ; x<=3 ; x++)
           p+=x;
        System.out.print(p);
        String r=reverse(p);
        System.out.print(r);
        but there is an error at the fifth line
        I want to know how to uese the reverse method and print the reversed string

        thank u
        try StringBuilder
        Code:
          String p="hello sam";
          System.out.println(p);
          StringBuilder s=new StringBuilder(p);
          String r=s.reverse().toString();
          System.out.println(r);

        Comment

        Working...