1

I'm trying to make a method that will take an array of strings and return an array with all the words in reverse order but my code is not working.

When I run it i get "[Ljava.lang.String;@74122d9c"

Test case: String[]words={"Monday","Tuesday","Wednesday"}; -->{"yadnoM","yadsueT","yadsendeW"};

public String[] reverseString(String[] words)
{
    String[] t=new String[words.length];

    for(int i=0;i<words.length;i++)
    {
        for(int j=words[i].length()-1;j>=0;j--)
        {
            t[i]+=words[i].substring(j,j+1);
        }
    }
    return t;
}
Justin
  • 21
  • 1
  • 1
  • 5

7 Answers7

3

When I run your code, I didn't get the same error that you posted, but I did notice that null was at the end of each reversed word.

nullyadnoM
nullyadseuT
nullyadsendeW

Which is beacuse when you create a new string array, all it's values default to null:

String[] t = new String[words.length];

The easiest way to fix it is to set it's value to an empty string, before you start adding to it:

public static String[] reverseString(String[] words)
{
    String[] text = new String[words.length];

    for (int i = 0; i < words.length; i++)
    {
        text[i] = "";
        for (int j = words[i].length() - 1; j >= 0; j--)
            text[i] += words[i].charAt(j);
    }
    return text;
}

I have tested this code, and it works perfectly fine for me.

To output the array, instead of using

System.out.println(words);

use the following:

System.out.println(Arrays.toString(words));

This will give you the output:

[yadnoM, yadseuT, yadsendeW]
Shadow
  • 3,926
  • 5
  • 20
  • 41
2

try using StringBuilder.reverse

public String[] reverseString(String[] words) {
        String[] t = new String[words.length];
        for (int i = 0; i < words.length; i++) {
            t[i]= new StringBuilder(words[i]).reverse().toString();
        }
        return t;
    }

Update

The fact that you are getting When I run it i get "[Ljava.lang.String;@74122d9c" is beccase you are printing the whole String array as one [Ljava.lang.String means String array. You will need to iterate over the array to print out the Strings one-by-one

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • 1
    We did not learn StringBuilder in my class, I don't think my teacher will let me use it – Justin Dec 12 '14 at 04:11
  • 3
    Why on earth not - it is in the java.lang package. – Scary Wombat Dec 12 '14 at 04:15
  • @ScaryWombat Why do one usually take classes? To learn things right? So the purpose of this assignment is not to reverse a string but to understand how one would do it? – Emz Dec 12 '14 at 04:17
  • @Emz Yeah I know that could be one lesson, another could be to learn that Strings are immutable. - See my update – Scary Wombat Dec 12 '14 at 04:19
  • Which is why he is returning a new string? Iterate backwards, copy over the value to the new, return. Voila. – Emz Dec 12 '14 at 04:19
  • @Emz He is NOT returning a new String or even creating a new String. He is creating a new String Array which is a good approach – Scary Wombat Dec 12 '14 at 04:22
  • Is there a way I can edit my code to get it to work without using reverse(). The code seems correct to me I just don't know why it doesn't work since I'm creating a new array. – Justin Dec 12 '14 at 04:24
  • user3189142 posted one without `StringBuilder`. It is **not** needed to use it. – Emz Dec 12 '14 at 04:24
2

You can transform your string into StringBuilder and it had reverse method. And its always better to use foreach rather than for, until there is actual need.

public String[] reverseString(String[] words) {
    String[] t = new String[words.length];
    for (String wordTemp : words) {
      StringBuilder sb = new StringBuilder(wordTemp);
      t[i] = sb.reverse().toString();   
    }
    return t;
}

Alternate approach :-

public  String[]  reverseString(String[] words)
{
    String[] t=new String[words.length];

    for(int i=0;i<words.length;i++)
    {   
        //added for setting elemennt as emptyString instead of null
        t[i] = "";
        for(int j=words[i].length()-1;j>=0;j--)
        {
            t[i]+=words[i].substring(j,j+1);
        }
    }

    //using loop
    for(int i=0;i<words.length;i++)
    {
         System.out.println(t[i]);
    }
    //using Arrays Method
    System.out.println(Arrays.toString(t));
    return t;
}
Panther
  • 3,312
  • 9
  • 27
  • 50
1
 public static void main(String[] args) {
        String[] words = { "Monday", "Tuesday", "Wednesday" };
        for (int i = 0 ; i < words.length ; i++) {
            words[i] = Reverse(words[i]);
        }
        for (int i = 0 ; i < words.length ; i++) {
            System.out.println(words[i]);
        }

    }

    private static String Reverse(String str) {
        StringBuilder result = new StringBuilder();
        StringTokenizer st = new StringTokenizer(str, "");
        while (st.hasMoreTokens()) {
            StringBuilder thisToken = new StringBuilder(st.nextToken());
            result.append(thisToken.reverse() + " ");
        }
        return result.toString();
    }

Output

yadnoM 
yadseuT 
yadsendeW 

Also you can use org.apache.commons.lang3.StringUtils;, just to reduce your effort/shorten the code

private static String Reverse(String str) {
        return StringUtils.reverse(str);
    }
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
1

Below Code is working fine with the help Stringbuilder reverse function.

public class Example {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] irreverseStr = {"Monday","Tuesday","Wendesday","Thursday","Friday","Saturday","Sunday"};           
    String[] reverseStr = new Example().getReverseArray(irreverseStr);

    for(int j = 0; j < reverseStr.length; j++){
        System.out.println(reverseStr[j]);
    }           
}

public String[] getReverseArray(String[] str){      
    String [] reversestr = new String[str.length];      
    for(int i=0;i<reversestr.length;i++){
        reversestr[i] = new StringBuilder(str[i]).reverse().toString();
    }       
    return reversestr;
}

}

Ravi Durairaj
  • 821
  • 7
  • 5
0
public static String[] reverseString(String[] words) {
    String[] t = new String[words.length];
    for (int i = 0; i < words.length; i++) {
        t[i]=new StringBuffer(words[i]).reverse().toString();

    }
    return t;
}

try StringBuffer's reverse method

Arun Xavier
  • 763
  • 8
  • 47
0

java 8+

public String[] reverseStringArray(String[] test){
       String[] result = Arrays.stream(test).map(item -> {
            List<String> list = Arrays.asList(item.split(""));
            Collections.reverse(list);
            return String.join("", list);
        }).collect(Collectors.toList()).toArray(new String[0]);
        return result;
}
saeed eivazi
  • 818
  • 1
  • 7
  • 14