I am trying to get this program to cancel itself after running 3 times, but I keep getting a “The local variable taskId may not have been initialized” error. For one is this dangerous. Two can I still properly compile it and run the program despite getting compiler errors? Lastly how would I fix this? Thanks!
final int taskId = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
int count = 0;
@Override
public void run() {
((LivingEntity) e.getEntity()).damage(2);
count++;
if (count > 2) {
Bukkit.getScheduler().cancelTask(taskId);
}
}
}, 60L);
It is possible you will try to use the taskId before it is initialised.
This will not work in your case, because it is not access only in
cancelTask(taskId)but when the anonymous class is constructed. i.e. before it has been set.A work around is to use a
int[] taskinstead but this is risky.A simpler work around is to throw a RuntimeException such as
IllegalStateExceptionor one of your own as this will stop the task repeating.