开发者

ArrayIndexOutOfBoundsException with an array that is large enough to hold the data I give it

开发者 https://www.devze.com 2023-03-17 09:14 出处:网络
I\'ve made the following method: static int GenerateSeccondPal(int x){ String y = Integer.toString(x); char[] z1 = y.toCharArray();

I've made the following method:

static int GenerateSeccondPal(int x){
    String y = Integer.toString(x);
    char[] z1 = y.toCharArray();
    char[] z2 = new char[y.length() / 2];

    for (int count = (z1.length /2); count <= z1.length; count++) {
        z2[count] = z1[count];
    }
    return Integer.parseInt(new String(z2));

}

However, when I run it, I get this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at challenges.Problem_4.GenerateSeccondPal(Problem_4.java:31) at challenges.Problem_4.main(Problem_4.java:6)

Which is odd, because the other method I made:

static int GenerateFirstPal(int x) {
    String y = Integer.toString(x);
    char[] z1 = y.toCharArray();
    char[] z2 = new char[z1.length / 2];

    for (int count = 0; count < z1.length / 2; count++) {
    开发者_JAVA技巧    z2[count] = z1[count];
    }
    return Integer.parseInt(new String(z2));

}

Works perfectly. What is wrong with what I have written?


Others have pointed out the array problems, but I don't see why you're using arrays at all. Just use substring:

static int generateFirstPal(int x) {
    String y = String.valueOf(x);
    String firstPart = y.substring(0, y.length() / 2);
    return Integer.parseInt(firstPart);
}

static int generateSecondPal(int x) {
    String y = String.valueOf(x);
    String secondPart = y.substring(y.length() / 2);
    return Integer.parseInt(secondPart);
}

Frankly this seems like an odd design anyway... are you sure this is the right behaviour in the first place? Given that you're dealing with numbers, it's not clear why you need a string representation at all. Depending on the expected length of the strings, I'd expect something like this:

static int generateFirstPal(int x) {
    return x / 1000;
}

static int generateSecondPal(int x) {
    return x % 1000;
}

This will split 123456 into 123 and 456, for example. Adjust the 1000 according to your real values.


Your <= should probably be a < to avoid that exception.


Your count variable is not starting from 0, so you have to rest the amount so that z2[count] starts from 0 in the for instead of starting from z1.length / 2


THe moment you do it:

for (int count = (z1.length /2); count <= z1.length; count++)
{ 
 z2[count] = z1[count];
} 

Supposing z1.length is 7 and z2.length is 4 it means that your program will crash because z2 does not have an index 4, only 3 at maximum.

I think you should start your counter = 0 and iterate while count < z2.length if you want to copy the first positions of the first array to the second;

0

精彩评论

暂无评论...
验证码 换一张
取 消