I am printing documents in a MongoDB database with a DBCursor. When I use the while loop, it works fine.
DBCursor cursor = people.find(new BasicDBObject("isPerson",true));
while(cursor.hasNext()){
System.out.println(cursor.next());
}
cursor.close();
With a while loop, the documents are printed. When I use a for loop, I get an error.
cursor = people.find(new BasicDBObject("isPerson",true));
for(int a=0;a<cursor.length()-1;a++){
System.out.println(cursor.next());
}
cursor.close();
This is the error:
java.lang.IllegalArgumentException: Can't switch cursor access methods
at com.mongodb.DBCursor.checkIteratorOrArray(DBCursor.java:841)
at com.mongodb.DBCursor.next(DBCursor.java:168)
at mongotest.MongoTest.main(MongoTest.java:39)
But even when I get around the error with the following code, nothing is printed.
cursor = people.find(new BasicDBObject("isPerson",true));
int b = cursor.length()-1;
cursor = people.find(new BasicDBObject("isPerson",true));
for(int a=0;a<b;a++){
System.out.println(cursor.next());
}
cursor.close();
a < bis wrong, should bea < b + 1ora <= b. There arenelements satisfying0 <= x && x < nand this is usually what aforlooks like