2014-05-11 64 views
-3

我想通過串行讀取一個字符串,並將逗號分隔值形式的字符串解析爲一個數組。我似乎能夠做到這一點,因爲我可以讀取串行數據並將陣列記錄下來。我還能夠將數組的第一個元素存儲到另一個變量中。嘗試訪問數組中的任何其他元素時會出現問題。無法訪問數組中的第3個元素

import processing.serial.*; 
Serial myPort; 
String inString=""; 
PFont font; 
int line = 0; 

float kph = 0.00; 
float distance = 0; 


void setup() { 
    size(300, 300); //size(1920, 1080); 
    printArray(Serial.list()); 
    String portName = Serial.list()[0]; 
    myPort = new Serial(this, portName, 9600); 

    myPort.bufferUntil('\n'); 
    font = createFont(PFont.list()[6], 20); 
    textFont(font); 
} 

void draw() { 
    //The serialEvent controls the display 
    logSerialData(inString); 
    displayValues(); 
} 

void serialEvent(Serial myPort) { 

    // read a byte from the serial port: 
    String inString = myPort.readStringUntil('\n'); 
    // split the string into multiple strings 
    // where there is a "," 

    String[] items = split(inString, ','); 

    kph = float(items[0]); 

    print(inString); 
    print(items); 
    println(items[2]); //processing falls down here: Error, disabling serialEvent() for COM8 null 
    int size = items.length; 
    println(size); 
} 
+0

你有什麼問題訪問到'項目時[2]'? –

+0

你能列出你的打印報告的結果嗎? – Kingand

+0

在你使用它們之前,你能打印一些東西嗎?例如items.length,在你假設有三件以上的東西之前? NB'items [2]'是數組中的第三個元素,而不是第二個元素。 – EJP

回答

1

如果你所得到的錯誤是

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: ... 

這是因爲你的數組沒有items[2],這實際上是在數組中的第三個元素。

在Java中,數組從零開始。

所以第一項是items[0]

第二項是在items[1]

如何,您可以看到項目的一個例子是

public class Test 
{ 
    public static void main(String[] args) 
    { 
     String[] items ="a,b".split(","); 
     for (int i = 0; i < items.length; i++) 
     { 
      System.out.println("The item in the position "+i+" has the value "+items[i]); 
     } 

    } 
}