I am quite a newbie in OOP using java and I’m learning as I go, much with the help of this community.
I’ve built a program that uses one object for repeating a task which reads from an excel sheet over and over again and extract data from there.
I would like to know what are the best practices to initialize this task over and over again so I wont get out-of-bound indexes on arrays and other variable errors?
Here is the thread code I’m using to refresh the gui (and the reading from file over and over again). As you can see it’s calling some methods from a different class. When this methods are called – the local variables and array indexed are already holding some data from previous iteration:
public void check() {
Thread check = new Thread() {
public void run() {
for (;;) {
EventQueue.invokeLater(new Runnable() {
public void run() {
// Update GUI here on EventQueue.
try {
Task.readTasks();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
label.setText("Next Task Is: " + Task.printNextTask);
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
break;
}
if (killcheck)
break;
}
}
};
check.start();
}
public void stopChecking() {
killcheck = true;
}
}
Your question is very generic, so I’m afraid my answer is also pretty generic. To help avoid ArrayIndexOutOfBoundsExceptions, use the concise for-each syntax as much as possible on arrays and Iterable objects.
Maybe you would also find this answer to a question on work queues helpful.