java - How to update an element in an array? -
how can observation method increase single element in numberofobs array 1, every time use it?
i error: exception in thread "main" java.lang.arrayindexoutofboundsexception: 0
public class database { private arraylist <string> databaseofbirds = new arraylist<string>(); private int[] numberofobs = new int[databaseofbirds.size()]; public void add(string name, string latinname) { databaseofbirds.add(name + "(" + latinname + ")"); } public string observation(string birdname){ for(int = 0; < databaseofbirds.size(); i++) { if(databaseofbirds.get(i).contains(birdname)) { numberofobs[i]++; return ""; } } return "is not bird!"; } }
when create numberofobs array it's length zero, since @ point databaseofbirds empty. unless you're growing array in unlisted code you'll nullpointerexception first time find bird.
you fix making numberofobs list:
private list<integer> numberofobs = new arraylist<>(); then in add method add line:
numberofobs.add(0); finally, change
numberofobs[i]++; to
numberofobs.set(i, 1 + numberofobs.get(i));
Comments
Post a Comment