0

How do i make an array with the opposite letters of the first array im making? For example if the string is "Hello", i want to use arrays to print out "olleH". When i try to return the variables it tells me "String index out of range: -1". Can anyone please tell me why? This is my code so far:

public class april{


public static void main(String [] args){

System.out.println("What do you want backwards?");
System.out.println("Your new word is " + reverse(IO.readString()));

}

public static String reverse(String original){

    char [] letters = new char [original.length()];
    char [] opp = new char [original.length()];
    char c= 'a';
    char d= 'a';
    String word= " ";
    String opposite= " ";

    for (int x=0;x<original.length();x++){
        c = original.charAt(x);
        letters[x]= c;
        if (x!=0){
        d = original.charAt(-x-1);
        opp[-x]=d;
        }
        else if (x==0){
        d = original.charAt(-1);
        opp[x]= d; 
        }
        word += letters[x];
        opposite += opp[x];

    }

    return word;
    return opposite;
  • another problem i noticed is that for the negatives, if the loop were at zero, I wouldnt be able to print out a negative 0, because such a thing doesnt exist. How do I fix this? – Lotun Kanji Apr 07 '18 at 21:50
  • You could use a StringBuilder & invoke reverse() on it – nitnamby Apr 07 '18 at 21:56

3 Answers3

1

You're close! You just need to start at the other end of the String for the second array (with proper syntax):

for (int x = 0; x < original.length(); x++) {
    char c = original.charAt(x);
    char d = original.charAt(original.length() - x - 1);
    letters[x] = c;
    opp[original.length() - x - 1] = d;
}

Note: You also have to subtract 1 because both arrays and string indices are 0-indexed.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
1

I think this is a great way to do it.

public class Main {

    public static void main(String[] args) {
        String reversed = reverse("Hello");
        System.out.println(reversed);
    }

    private static String reverse(String word) {
        byte[] array = word.getBytes();
        int i = 0;
        int j = array.length - 1;
        byte tmp;
        while (j > i) {
            tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;
            j--;
            i++;
        }
        return new String(array);
    }
}
Eduardo Folly
  • 146
  • 2
  • 6
1

Your method receives a String and returns another String, so you don't need to work with arrays at all, just use the reverse method of the StringBuilder class.

public static String reverse(String original) {
    return new StringBuilder(original).reverse().toString();
}
Gabriel
  • 1,922
  • 2
  • 19
  • 37