i keep getting weird issues when i'm constructing ulam (prime) spiral. doing in spiralmaker() using 4 step method create spiral. long location less total squares in array, , on step 1 should move on 1 step right , place 2. when hits step 2, moves 1 , places numlocation 3. on step 3 moves left twice taking 2 steps , setting locations 4 , 5, etc.
but when i'm running this, below exception on line 32,
exception in thread "main" java.lang.arrayindexoutofboundsexception: 5
import java.util.arrays; public class gridmaker { private static int gridrow = 5; // r = length private static int gridcol = 5; // c = height private static int[][] grid = new int[gridrow][gridcol]; private static int totalsteps = (gridrow * gridcol); // total blocks on grid private static int numlocation = 1; // location refers number in box, ie. 1, 2, 3, etc. private static int rowlength = 1; private static int collength = 1; public static void main(string[] args) { grid[calc.findarraycenter(gridrow)][calc.findarraycenter(gridrow)] = 1; spiralmaker(); (int r = 0; r < gridrow; r++){ (int c = 0; c < gridcol; c++){ system.out.print(grid[r][c] + " "); } system.out.println(""); } } private static void spiralmaker() { (int stepmaker = 0; stepmaker < 4; stepmaker++){//counter steps, needs 1 of these if (stepmaker == 1 && numlocation < totalsteps){ (int r = 0; r < gridrow; r++){ //starts browsing array last number (int c = 0; c < gridcol; c++){ if(grid[r][c] == (numlocation - 0)){ //when finds last number for(int = 0; < rowlength; i++){ grid[r][c + 1] = numlocation + 1; //when 0 no errors, when 1 "java.lang.arrayindexoutofboundsexception" } numlocation++; rowlength++; } } } } } } } // ----------------------- public class calc { public static int findarraycenter(int center) { int fcenter = 0; if (center % 2 != 0) fcenter = (int) ((center / 2)); else fcenter = (center / 2); return fcenter; } public static boolean isodd(int num) { boolean result = true; if (num % 2 == 0) result = false; // false = even, true = odd return result; } public static boolean primetester(int num) { if (num == 1) return false; if (num % 2 == 0 && num != 2) return false; (int primecheck = 3; primecheck <= num / 2; primecheck += 2) { if (num % primecheck == 0 && num != primecheck) return false; } return true; } }
it looks running loop 1 many iterations. because array [5][5] , using [r][c+1] never want c 4.
change
for (int c = 0; c < gridcol; c++){
to
for (int c = 0; c < gridcol-1; c++){
and see if works
Comments
Post a Comment