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;
}
2
  • what is your output? what kind of error message u get? Commented Dec 12, 2014 at 4:07
  • Did you try using a for loop to iterate over the array and using a string builder str.reverse() method? that should work Commented Dec 12, 2014 at 4:09

7 Answers 7

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]
Sign up to request clarification or add additional context in comments.

Comments

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;
}

3 Comments

We did not learn StringBuilder in my class, I don't think my teacher will let me use it
you can use any of approach to print array, Arrays is what we use, don't know if your teacher will let you use.
where did that "i" in t[i] came from?
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

8 Comments

We did not learn StringBuilder in my class, I don't think my teacher will let me use it
Why on earth not - it is in the java.lang package.
@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 Yeah I know that could be one lesson, another could be to learn that Strings are immutable. - See my update
Which is why he is returning a new string? Iterate backwards, copy over the value to the new, return. Voila.
|
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);
    }

Comments

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;
}

}

Comments

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

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.