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++) {
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: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:
This will split 123456 into 123 and 456, for example. Adjust the 1000 according to your real values.