我有一段代码可以在flickr上进行图像搜索,并返回带有该名称的第一张图像的URL。我在flickr上搜索的某些单词没有任何匹配的图像,因为没有图像可以得到一个ArrayOutOfBoundsException [0]。有没有办法可以让程序跳过那些特定的单词并继续搜索下一个单词?
到目前为止,这是我的代码:
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() {
}
答案 0 :(得分: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
阵列执行此操作了!