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?
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:
Also the getTokens function could be implemented easier as well: