简体   繁体   中英

School Project, Array Index Out of Bounds Exception: 2

I'm currently working on a project for school and am following a video tutorial, I'm pretty new to coding. From what I can tell everything looks right but when I run the preview it sends me a blank window with the error "ArrayIndexOutOfBoundsException:2"

PShape baseMap;
String csv[];
String myData[][];

//Setup BaseMap and csv info

void setup() {
 size(1800, 900);
 noLoop();
 baseMap = loadShape("WorldMap.svg");
 csv = loadStrings("FlightCancellations.csv");
 myData = new String[csv.length][4];
 for(int i=0; i<csv.length; i++) {
 myData[i] = csv[i].split(",");

  } 
}


//draw
void draw() {
  shape(baseMap, 0, 0, width, height);
  noStroke();
  fill(255, 0, 0, 50);

  for(int i=0; i<myData.length; i++){


    float graphLong = map(float(myData[i][2]), -180, 180, 0, width);
   float graphLat = map(float(myData[i][3]), -90, 90, 0, height);

          println(graphLong + " / " + graphLat);

   ellipse(graphLong, graphLat, 10, 10);

  }
}

Also, the mapped image works fine until I add

for(int i=0; i<myData.length; i++){


    float graphLong = map(float(myData[i][2]), -180, 180, 0, width);
   float graphLat = map(float(myData[i][3]), -90, 90, 0, height);

          println(graphLong + " / " + graphLat);

You should get in the habit of checking that data exists before you use it in your program:

for(int i=0; i<myData.length; i++) {
    if (myData[i].length > 3) { // Check that the array has at least 4 entries
        float graphLong = map(float(myData[i][2]), -180, 180, 0, width);
        float graphLat = map(float(myData[i][3]), -90, 90, 0, height);
        println(graphLong + " / " + graphLat);
        ellipse(graphLong, graphLat, 10, 10);
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM