2

I am trying to reverse all the strings in an array in java, but seem to over write all of them with the first.

private static void palindrome(String[] s) {
    int flag=0;
    String reverse;
    for(int i=0;i<n;i++) // n is declared globally as number of strings
    {
        reverse="";
        for (int j=s[i].length()-1;i>=0;i--)
             reverse=reverse+s[i].charAt(j);
        if(s[i].equals(reverse))
            {
                System.out.println(s[i]);   
                flag=1;
            }
    }
    if(flag==0)
        System.out.println("There are no palindromic strings");
}
0

7 Answers 7

4

Try these steps:

String[] strDays = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday"};
List<String> list = Arrays.asList(strDays);
Collections.reverse(list);
strDays = (String[]) list.toArray();
Sign up to request clarification or add additional context in comments.

1 Comment

The best method, without time consume! great!
3

This line looks wrong:

for (int j = s[i].length()-1; i >= 0; i--)

It should be:

for (int j = s[i].length()-1; j >= 0; j--)

In other words: the indexes in the inner loop are mistaken, they should be using j instead of i. As a side comment - here's a simpler way to reverse a string:

reverse = new StringBuilder(s[i]).reverse().toString();

Comments

2

Looks like you used i instead of j in the inner loop.

 for (int j=s[i].length()-1;j>=0;j--)
      reverse=reverse+s[i].charAt(j);

Comments

1

I'd advise you to break even this small problem into chunks.

Write a separate method that reverses a single String. Get that working and tested. Only then should you iterate over a collection or array and apply it to each member.

You'd have an easier time debugging this if you did it in smaller steps. The fact that your string reversing method was borked would have been apparent right away.

You shouldn't write stuff to System.out like that from methods.

public static String reverse(String s) {
    StringBuilder reversed = new StringBuilder(s.length());
    // reverse one string here
    return reversed.toString();
}

public static String [] reverseAll(String [] originals) {
    String [] reversed = new String[originals.length];
    for (int i = 0; i < originals.length; ++i) {
        reversed[i] = reverse(originals[i]);
    }
    return reversed;
}

Comments

0

Your inner loop should be:

for (int j=s[i].length()-1; j>=0; j--){
     reverse=reverse+s[i].charAt(j);
     // ... //
}

Comments

0
for (int j=s[i].length()-1; j >=0; j-- )
                           ###   ### 

you need to correct your inner loop. Instead of i you need to use loop variable j.

Comments

0

Why are you using this:

 for (int j=s[i].length()-1;i>=0;i--)

You should use this instead:

 for (int j=s[i].length()-1;j>=0;j--)

Comments

Your Answer

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