0

This code isn't working. Can you tell me what's wrong and why?

package exer0403e08;


public class EXER0403E08 {
    public static void main(String[] args) {
        String str= "hello";
        System.out.println(str);
        char[]strchar = str.toCharArray();
        int first;
        int last=5;

        System.out.println("The reversed is: ");
        for (first=1; first<=5; first++){
            strchar[first]=strchar[last];


            last--;

        } 
        str=String.valueOf(strchar);
        str=str.toUpperCase();
        System.out.println(str);


    }

}

The answer is "OLLO" and i want to make it "OLLEH".

halfer
  • 19,824
  • 17
  • 99
  • 186
h.harry
  • 13
  • 4

3 Answers3

1

You loop have several problems. And you misunderstood the array indexes.

You are iterating and modifying the same array. Hence the weird behaviour and indexces will start from zero for arrays.

So the fixed code will be

public static void main(String[] args) {
        String str = "hello";
        System.out.println(str);
        char[] strchar = str.toCharArray();
        int first;
        int last = 4;

        System.out.println("The reversed is: ");
        for (first = 0; first < 5; first++) {
            strchar[first] = str.charAt(last);

            last--;

        }
        str = String.valueOf(strchar);
        str = str.toUpperCase();
        System.out.println(str);

    }

Update :

Demo link http://ideone.com/GfgDZ3

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

you can write your own method like this:

    public static String reverse(String str)
     {
     String reversed = new String();

     for ( int j = str.length()-1; j >= 0; j-- )
         reversed += str.charAt(j);

     return reversed;
     }

and then try reverse("Hello");

Eclipse
  • 175
  • 1
  • 12
  • that's complicated – h.harry Mar 12 '17 at 10:56
  • @h.harry well for your comments on other answer..s.o. is q&a site but a strict one which is why it has quality. Google for it. All the best for coding..and this ans is not complicated just index is reversed – minigeek Mar 15 '17 at 15:14
0

You have better methods in java to reverse string. Please check this answer :

You can use this:

new StringBuilder(hi).reverse().toString()

Or, for versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have the same API. Thanks commentators for pointing out that StringBuilder is preferred nowadays.

Community
  • 1
  • 1
Arun Shankar
  • 2,603
  • 2
  • 26
  • 36