1
public static void reverse(String[] array){
    String reverse = "";
    for(int i=0;i<array.length;i++){
        for(int j = array[i].length() - 1; j >= 0; i--)
        {
            reverse = reverse + array[i].charAt(i);
        }
    }
}

Using this method I am trying to reverse every single string in the string array but it just throws an exception. The array's length and elements are being inputed with scanner.

public static String[] arrayStringCreation(String[] array){
        boolean isArrayInputStillGoing = true;
        while (isArrayInputStillGoing){
            System.out.println();
            System.out.println("Input the size of the array");
            int sizeOfArray = scanner.nextInt();
            if (sizeOfArray <= 0){
                System.err.println("Size can't be less than 1");
                continue;
            }
            array = new String[sizeOfArray+1];
            System.out.println("Input words less than 20 symbols");
            for(int i=0;i<sizeOfArray+1;i++){
                array[i] = scanner.nextLine();
                if (array[i].length()>20){
                    System.err.println("Try again with a word with less than 20 symbols");
                    i--;
                }
            }
            isArrayInputStillGoing=false;
        }
        return array;
    }
2
  • 1
    Do you mean array[i].charAt(j)? Also, you're never resetting reverse to "" Commented May 18, 2020 at 19:44
  • FYI: char type in Java is obsolete. Use code point numbers instead. Commented May 18, 2020 at 20:46

5 Answers 5

5

StringBuilder::reverse

Simply iterate the array, and replace each entry with its reverse. You can use a StringBuilder to reverse a String, calling StringBuilder.reverse.

Like,

public static void reverse(String[] array) {
    for (int i = 0; i < array.length; i++) {
        array[i] = new StringBuilder(array[i]).reverse().toString();
    }
}

And then to test it

public static void main(String[] args) {
    String arr[] = { "abc", "def" };
    reverse(arr);
    System.out.println(Arrays.toString(arr));
}

See this code run live at IdeOne.com.

[cba, fed]

Sign up to request clarification or add additional context in comments.

10 Comments

I tried using that but I still get the same exception Exception in thread "main" java.lang.NullPointerException
@NotJhonWick45 that must be because there are nulls in the array.
When I create the array it prints out the contents and they are the same as I have inputed I don't see any nulls
@NotJhonWick45 The first line of the stack trace should tell you exactly which line is throwing the nullpointerexception. Are you certain the exception is from this method? Post a reproducible example. Because this code will reverse String(s).
at java.lang.StringBuilder.<init>(StringBuilder.java:112)
|
1

Stream

The Answer by Elliott Frisch is correct and robust, and should be accepted.

In addition, for fun, here is a version of that code using streams rather than the conventional for loop. I am not claiming this is better.

I do not know of a way for a stream of an array to affect that array. So instead here I make and return a fresh array.

public static String[] reverse( String[] array ) {
    Objects.requireNonNull( array , "Received null argument where an array of `String` was expected. Message # b5c03336-4b9e-4735-a054-16e43aac059e.") ;
    
    Stream< String > stream = Arrays.stream( array ) ;
    String[] result =
            stream
            .map( ( String s ) -> new StringBuilder( s ).reverse().toString() )
            .toArray(String[]::new) 
    ;
    
    return result ;
}

Usage.

    String arr[] = { "abc" , "def" , "mask😷" } ;
    String arr2[] = Ideone.reverse( arr ) ;
    
    System.out.println( Arrays.toString( arr ) ) ;
    System.out.println( Arrays.toString( arr2 ) ) ;

See that code run live at IdeOne.com.

[abc, def, mask😷]

[cba, fed, 😷ksam]

Comments

1

You can use StringUtils.reverse of org.apache.commons.lang3 from the Apace Commons project. That method handles null.

public static void reverse(String[] array) {
    for (int i = 0; i < array.length; i++) {
        array[i] = StringUtils.reverse(array[i]);
    }
}

3 Comments

it says "Cannot resolve method reverse in StringUtils"
Maybe you didn't import StringUtils.
@NotJhonWick45 This Answer uses a library from Apache Commons. You will need to obtain that library and add to your project to utilize this approach.
0

You didn't update the array with the reverse string and decrement j in the inner loop

    public static void reverse(String[] array) {
        String reverse;
        for (int i = 0; i < array.length; i++) {
            reverse = "";
            for (int j = array[i].length() - 1; j >= 0; j--) {
                reverse += array[i].charAt(j);
            }
            array[i] = reverse;
        }
    }

, main

    public static void main(String[] args) {
        String arr[] = { "head", "body", "hand" };
        reverse(arr);
        System.out.println(Arrays.toString(arr));
    }

, output

[daeh, ydob, dnah]

4 Comments

yeah thanks I did that and it worked but the main problem was that I was inputing by error a null array and not the one I had created with scanner.
Caution: This code fails with more than half of the characters defined in Unicode. See a failing example of this code run live at IdeOne.com. The char type in Java is obsolete. Use Unicode code point numbers instead. For a robust solution, see the Answer by Elliott Frisch.
@BasilBourque I have corrected the posted code in the question and it's simple for the ASCII
Expecting only ASCII characters is not very realistic. So too expecting only Basic Multilingual Plane is not very realistic. Even ignoring foreign languages, the use of certain symbols and emojis will break this code. In the year 2020, it really is time to learn how to use code point numbers rather than char type.
0

Here is another option. It will work in most versions of Java. Instead of returning a new Array, it simply modifies the one that is passed.

public class ReverseStringsInArray {
    public static void main(String[] args) {
        String [] strArr = {"alpha", "beta","gamma","delta"};
        reversed(strArr);
        for (String v : strArr) {
            System.out.println(v);
        }
    }

    public static void reversed(String[] arr) {
        int k = 0;
        for (String v : arr) {
            int[] s = v.codePoints().toArray();
            int len = v.length();
            // swap the outer characters as the pointer moves
            // towards the middle
            for (int i = 0; i < len >> 1; i++) {
                int cp = s[i];
                s[i] = s[len - i - 1];
                s[len - i - 1] = cp;
            }
            arr[k++] = new String(s,0,s.length);
        }
    }
}

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.