java - Can't figure out ArrayIndexOutOfBoundsException: -1 -
this question has answer here:
i have make program makes square looks this:
|8|1|6|
|3|5|7|
|4|9|2|
it places incremented number each turn, placement of 1 block , 1 block right. n size of square, , must odd. above example has n of 3. handle edges of array, there 3 rules.
1) if row = -1 (the placement goes on top of array), row = n-1
2) if col = n (the placement goes past right edge of array), col = 0
3) if current placement filled or if row = -1 && col = n, placement instead goes below last placement
i've concluded rule 3 should checked before rule 1 , 2. wrote program print row , col instead of placing them in array diagnostic purposes. reason, rule 3 if statement causes -1, out of array's bounds, causing "arrayindexoutofboundsexception: -1". see did wrong? have rule 1& 2 commented out, i'm pretty sure doesn't have them.
//finds how many numbers placed based on //number of squares filled int simcount = n*n; int i; //for loop keeps track of how many squares filled for(i = 1; i<simcount; i++) { r = r - 1; //moves placement row c = c + 1; //moves placement col if(square[r][c]>0 || (r==-1 && c==n)) { //rule 3 r = r+2; c = c-1; } //if(r==-1) //rule 1 // r=n-1; //if(c==n) //rule 2 // c=0; system.out.println("r:"+r + " c:"+c); }
swap order of tests (but alone won't solve issue; see below):
if( (r==-1 && c==n) || square[r][c]>0 ) in posted code, square[r][c] must evaluated before r==-1 && c==n, because conditional operator operands evaluated left right. if r==-1 && c==n true, square[-1][n] evaluated, hence exception.
however, evaluation of conditional expression stops result known, if swap order, won't attempt evaluate square[r][c] if first condition true (as true || anything true).
from jls 15.24 (regarding conditional-or):
at run time, left-hand operand expression evaluated first ...
if resulting value true, value of conditional-or expression true , right-hand operand expression not evaluated.
if value of left-hand operand false, right-hand expression evaluated; ...
... right-hand operand expression evaluated conditionally rather always.
however, careful. evaluating rule 3 first, still may run condition r==-1 c!=n, in case square[-1][c] evaluated , throw exception. may still have rearrange bit anyways work, e.g.:
if ( (r==-1 && c==n) || (r!=-1 && c!=n && square[r][c]>0) ) { which getting ugly. may clearer split rule 3 , use else properly:
if (r == -1 && c == n) { // rule 3a } else if (r == -1) { // rule 1 } else if (c == n) { // rule 2 } else if (square[r][c] > 0) { // rule 3b } of course, rework algorithm taking advantage of % (modulo) (with trick make wrap around negative numbers):
static int nmod (int a, int b) { return ((a % b) + b) % b; } // then: for(i = 1; i<simcount; i++) { r = nmod(r - 1, n); c = nmod(c + 1, n); if (square[r][c] > 0) { r = nmod(r + 2, n); c = nmod(c - 1, n); } ... }
Comments
Post a Comment