1

我希望将以下字符串存储到一个数组中,但它会引发 ArrayOutOfBound 异常。

public static void main(String[] args) {
    // TODO Auto-generated method stub
    char[] arr = {};
    String str = "Hello My Name is Ivkaran";
    for (int i = 0;i < str.length(); i++){
        System.out.println(str.charAt(i));
        arr[i] = str.charAt(i);
    }
}
4

3 回答 3

5

You've declared an array of length 0 with this line:

char[] arr = {};

To assign anything to that array, it must be initialized to some non-zero size. Here, it looks like you need it to be the same size as the string.

String str = "Hello My Name is Ivkaran";
char[] arr = new char[str.length()];

You can also just call toCharArray() on the String to get a char[] with the contents copied into it already.

char[] arr = str.toCharArray();
于 2013-08-15T23:22:34.850 回答
3

Arrays are not dynamic in Java. Either use an arraylist or create the array with a dimention as:

char[] arr = new char[str.length()]

Also move this line below the

String str = "Hello My Name is Ivkaran";

Then continue as originally.

于 2013-08-15T23:22:30.240 回答
0

Just do this:

String str = "Hello My Name is Ivkaran"; 
char[] arr = str.toCharArray();
于 2013-08-15T23:22:47.493 回答