2016-01-07 84 views
0

我有一段代碼,它在flickr上進行圖像搜索並返回帶有該名稱的第一個圖像的URL。我在flickr上搜索的某些單詞沒有任何匹配的圖像,因爲沒有圖像可以獲取ArrayOutOfBoundsException [0]。有沒有一種方法可以讓程序跳過特定的單詞並繼續搜索下一個單詞?arrayoutofboundsexception當使用flickr api

這是我到目前爲止的代碼:

PImage[] images; 
int imageIndex; 
XML xml; 
String tag = "rutte"; 
String tag_mode = "all"; 
String words[]; 

void setup() { 
    size(50, 50); 
    String lines[] = loadStrings("text.txt"); 
    words = split(lines[0], " "); 


for (int k = 0; k<words.length; k++) { 
String query = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY API KEY&tags="+ words[k] + "&sort=relevance&tag_mode="+ tag_mode +"format=rest"; 
xml = loadXML(query); 
XML[] children = xml.getChildren("photos"); 
if(children.length > 0){ 
XML[] childPhoto = children[0].getChildren("photo"); 


    for (int i = 0; i < 1; i++) { 
    String id = childPhoto[i].getString("id");  // this line generates the error :(
    String title = childPhoto[i].getString("title"); 
    String user = childPhoto[i].getString("owner"); 
    String url = "https://www.flickr.com/photos/"+user+"/"+id; 
    println(url); 
    println("====================="); 
    } 
} 
} 

textAlign(CENTER, CENTER); 
smooth(); 
} 

void draw() { 
} 

回答

1

只要用你的陣列的length領域。事情是這樣的:

XML[] children = xml.getChildren("photos"); 
if(children.length > 0){ 
    XML[] childPhoto = children[0].getChildren("photo"); 

    if(childPhoto.length > 0){ 
     String id = childPhoto[0].getString("id"); 
     //rest of your code 
    } 

可以在the Processing reference找到更多信息。

實際上,您已經在使用words陣列進行此操作!

+0

查看我的帖子獲取更新的代碼。但我不斷收到arrayoutofboundsexception:0錯誤請參閱生成錯誤的行的註釋 – FutureCake

+0

@FutureCake你只需要用'childPhoto'數組做同樣的事情。我編輯了我的示例以包含該部分。 –

+0

它工作真棒感謝凱文的所有幫助:D – FutureCake