首页 文章

Arduino to Processing,Strings ArrayIndexOutOfBoundsException:18

提问于
浏览
1

我正在开发一个程序,它将消息从Arduino发送到Processing,将它们从arduino打印到串口作为十进制数字,然后在处理中将它们拾取到字符串数组中 . 我得到的问题是:“ArrayIndexOutOfBounds:18”它突出显示dlay = Integer.parseInt(B [18])的行,我假设数组不足以存储超过17的任何东西,我'我可能犯了一个非常愚蠢的错误,但我无法弄清楚如何扩展它!

有什么建议?

非常感谢提前!

import processing.serial.*; //import the Serial library

int end = 10;
String serial;
Serial port;
int c;
int d;
int e;
int f;
int g;
int a;
int b;
int C;
int p1t;
int p2t;
int p3t;
int p4t;
int p5t;
int p6t;
int p7t;
int p8t;
int pan;
int reverb;
int dlay;
int distort;
//ellipse parameters
int noteOn = 0;
int col1 = 0;
int col2 = 0;
int col3 = 0;
String[] A;
String[] B;
void setup() {
    size(600,600);
    frameRate(30);
    port = new Serial(this, Serial.list()[7], 115200);
    port.clear();
    serial = port.readStringUntil(end);
    serial = null; // initially, the string will be null (empty)
}

void draw() {

while (port.available() > 0) { 
serial = port.readStringUntil(end);

}
if (serial != null) {  //if the string is not empty, print the following

  A = split(serial, ','); 
  B = trim(A);
  c = Integer.parseInt(B[1]);
  if (c == 1){
  col1 = 255;
  col2 = 0;
  col3 = 0;
  }
  d = Integer.parseInt(B[2]);
  if (d == 1){
  col1 = 0;
  col2 = 0;
  col3 = 255;
  }
  e = Integer.parseInt(B[3]);
  if (e == 1){
  col1 = 0;
  col2 = 255;
  col3 = 0;
  }
  f = Integer.parseInt(B[4]);
  if (f == 1){
  col1 = 255;
  col2 = 0;
  col3 = 255;
  }
  g = Integer.parseInt(B[5]);
  if (g == 1){
  col1 = 255;
  col2 = 255;
  col3 = 0;
  }
  a = Integer.parseInt(B[6]);
  if (a == 1){
  col1 = 0;
  col2 = 255;
  col3 = 255;
  }
  b = Integer.parseInt(B[7]);
  if (b == 1){
  col1 = 50;
  col2 = 250;
  col3 = 130;
  }
  C = Integer.parseInt(B[8]);
  if (C == 1){
  col1 = 200;
  col2 = 90;
  col3 = 75;
  }
if(c == 1 || d == 1 || e == 1 || f == 1 || g == 1 || a == 1 || b == 1 || C == 1){
  noteOn = 1;
}
else {
  noteOn = 0;
}
p1t = Integer.parseInt(B[9]);
p2t = Integer.parseInt(B[10]);
p3t = Integer.parseInt(B[11]);
p4t = Integer.parseInt(B[12]);
p5t = Integer.parseInt(B[13]);
p6t = Integer.parseInt(B[14]);
p7t = Integer.parseInt(B[15]);
p8t = Integer.parseInt(B[16]);
pan = Integer.parseInt(B[17]);
dlay = Integer.parseInt(B[18]);
//reverb = Integer.parseInt(B[19]);
//distort = Integer.parseInt(B[18]);
} 
fill(0, 0,0, 255);
rect(0,0, 600,600);
fill(col1,col2, col3); 
ellipse(300+pan, 300, (noteOn*p8t), (noteOn*p8t));


}

1 回答

  • 0

    你是否意识到Java中的数组(以及因此也是处理)在 0 开始索引,而不是 1 ?也就是说,通过编写 exampleArray[0] 来访问名为 exampleArray 的数组的第一个元素,使用 exampleArray[1] 访问第二个元素,等等 . 因此,如果数组中有18个元素,则写入 B[18] 实际上是在尝试获取不存在的第19个元素 .

    旁注:有这么多变量的做法很糟糕,特别是有这么短的名字 - 我不知道 abc 等正在通过查看他们的名字来做什么,后面的代码没有't explain it either. This is compounded by the fact that there are both lower- and upper-case versions of some of the letters! You know what they are now, but if you come back to this code in a few months then you' ll必须想办法 .

相关问题