1

I tried the following, but I always get an error message. ("Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10")

public class rechner2 {
    static String a = "7289347928";

    
    public static void main(String[] args) {
        for (int i = 0; i < a.length(); i++) {
            System.out.println(langeZahl(a)[i]);
        }
    }
    
    
    private static char[] langeZahl(String a) {
         if (a == null) {
             return null;
         }

         int len = a.length();
         char[] array = new char[len];
         for (int i = 0; i <= len; i++) {
             array[i] = a.charAt(a.length() - i);
         }
         return array;
    }
}

I don't get it.

Mar
  • 43
  • 3

2 Answers2

1

arrays end at the index of length-1. if you want to do it this way you'll need to have the line where you're creating the reverse array say:

array[i] = a.charAt(a.length() - i - 1);

it's trying to get the character at a[a.length]
which is impossible because the indexes go from 0 -> length-1

Rage Man
  • 41
  • 1
  • 6
0

your error is in your for. In your first for you use i < a.length() but in ypur second for you use i <= len and you will need another 'counter' to keep the position of the 'a' array you are getting the chars from. The fixed code will be this one:

static String a = "7289347928";

public static void main(String[] args) {
    for (int i = 0; i < a.length(); i++) 
    {
        System.out.println(langeZahl(a)[i]);
    }
}


private static char[] langeZahl(String a) {
     if (a == null) {
         return null;
     }

     int len = a.length();
     int j = len-1;
     char[] array = new char[len];
     for (int i = 0; i < len; i++) {
         array[i] = a.charAt(j);
         j--;
     }
     
     return array;
}