Sorry, it may be a dumb question, but I'm a total a beginner : When I try to execute the following program, it compiles, but I get the following error:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at Numbers.main(Numbers.java:6)"
Can someone help?
public class Numbers {
public static void main (String[] args) {
int [] harry = new int [25];
for (int i = 0, n = 12; i < harry.length; i++, n--) {
if (i % 2 > 0) {
harry[n] = i;
}
}
for (int j = 0, m = 25; j < harry.length; j++, m--) {
if (j % 2 == 0) {
harry[m] = j;
}
}
for (int k = 0; k < harry.length; k++) {
System.out.println(harry[k]);
}
}
}
You have this kind of runtime exception because you try to get harry[-1], but it's impossible. You will also see this exception in the second for, because you set m = 25, but indexces of your array are from 0 to 24. Set n=harry.length-1 and m = harry.length-1, then your program will work.
On the following line,
for (int j = 0, m = 25; j < harry.length; j++, m--) {
m = 25, it should be 25-1, otherwise it will throw index out of bound exception
Besides having to initialize m
to harry.length - 1
(since 25 is out of bounds), you should only decrement n
and m
when you use them (ie when you assign a value to the harry
array):
int [] harry = new int [25];
for (int i = 0, n = 12; i < harry.length; i++) {
if (i % 2 > 0) {
harry[n] = i;
n--;
}
}
for (int j = 0, m = harry.length - 1; j < harry.length; j++) {
if (j % 2 == 0) {
harry[m] = j;
m--;
}
}
Otherwise, n
will become negative before the first loop is done, and m
will become too small.
I am not sure if I understand everything but I believe if you do this your code should work perfectly:
Use if (i % 2 > 0 && n >= 0)
instead of if (i % 2 > 0)
and use if (j % 2 == 0 && m<=24)
instead of if (j % 2 == 0)
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.