-2

Could any one help me fix this Exception error?Thanks in advance.

error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
    at HelloWorld.main(HelloWorld.java:13)

error pointing at this line:

String str2 = str + (toCharArray[toCharArray.length] + String.valueOf(i));

java code:

import java.util.Calendar;

import java.util.TimeZone;

public class HelloWorld {
  public static void main(String[] args) {
    //System.out.println("Hello World");
        char[] toCharArray = String.valueOf((Calendar.getInstance(TimeZone.getTimeZone("utc")).getTimeInMillis() + 1825) ^ 16842788).toCharArray();
        String str = "";
        //String str2 = "";
        int i = 0;
        while (i < toCharArray.length) {
            String str2 = str + (toCharArray[toCharArray.length] + String.valueOf(i));
            i++;
            str = str2;
        }

        System.out.println("value of str:");
        System.out.println(str);
  }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
user1788736
  • 2,727
  • 20
  • 66
  • 110
  • If you change the error line to String str2 = str + (toCharArray[toCharArray.length-1] + String.valueOf(i)); exception will go away. But the answer will be all digits (if that is what you want). – Pramod Jul 17 '17 at 00:12

2 Answers2

0

The Index of an array is 0 based. You are trying to access an element that does not exist. If you want to get the last element, you should do it as shown below.

toCharArray[toCharArray.length - 1]

Rajesh P
  • 343
  • 1
  • 8
  • Thanks for replies . I tried using toCharArray[toCharArray.length - 1] but still same error! should i declare the str2 as string outside while loop ? – user1788736 Jul 17 '17 at 00:10
  • I ran the code after changing to CharArray[toCharArray.length - 1] and it worked fine. Did you recompile after changing the code ? – Rajesh P Jul 17 '17 at 00:39
0

I believe the index you want to use in loop is i and not toCharArray.

toCharArray[toCharArray.length] will always throw an exception because the range of the array goes from 0 to length-1.

Maaaatt
  • 429
  • 4
  • 14