I have implemented this code

import java.util.ArrayList;
import java.util.List;

public class Client {
    String data;

    public String[] getTokens(String data) {

        List<String> arrl=new ArrayList<String>();

        for (String tokens : data.split(" "))
        {
            System.out.println(tokens);
            arrl.add(tokens);
        }

        String[] arr;
        arr=(String[]) arrl.toArray(new String[arrl.size()]);
        return arr;





    }

    public String reverseandappend(String[] data) {

        StringBuffer strbuf=new StringBuffer();
        StringBuffer temp=new StringBuffer();

        int i=0;
        for(i=0;i<data.length;i++)
        {
            strbuf.append(data[i]+" ");

            temp.append(strbuf.reverse().toString());
            ;
        }
            return temp.toString();



    }

    public static void main(String[] args) {

        Client cl=new Client();
        String[] tokens=cl.getTokens("Hello World");

        String data=cl.reverseandappend(tokens);
        System.out.println(data);

    }
}

but the output generated is

Hello
World
 olleH dlroWHello 

where required output is just

olleH dlroW

What causes the wrong output?

3

There are 3 answers

0
The Javatar On

The first to lines in your "wrong output" are generated in your getTokens function: System.out.println(tokens); About the 3rd line that have olleH dlroWHello because the reverseappend function doesn't work properly.

You cand do the reverseappend much more easier:

public String reverseandappend(String[] data) {

    StringBuilder builder;

    for(int i=0;i<data.length;i++)
    {
        builder.append(data[i].reverse());
        builder.append(" ");
    }
    return builder.toString();
}

Also the getTokens function could be implemented easier as well:

public String[] getTokens(String data) {

        return data.split(" ");
  }
0
LeTex On

Bug in your code

       for(i=0;i<data.length;i++)
        {
            strbuf.append(data[i]+" ");

            temp.append(strbuf.reverse().toString());

            //Clear the SB
            strbuf.setLength(0);
        }
0
Mureinik On

You keep appending to strbuf, which will make each iteration append all the array elements up to the current one instead of just the current one - you need to reset it on each iteration. (BTW - since these are local variables, it's perfectly safe to use StringBuilder instead of StringBuffer, thus gaining a slight performance improvement):

public String reverseandappend(String[] data) {
    StringBuilder res = new StringBuffer();

    for (String str : data) { 
        StringBuilder temp = new StringBuilder(str);

        res.append(temp.reverse()).append(' ');
    }
    return res.toString();
}