Donc, fondamentalement, j'ai un projet GridWorld que je fais en ce moment dans ma classe AP Comp Sci. Je fais Pacman. Voici mon code pour la méthode d'acte (pour ceux qui ne connaissent GridWorld, la méthode de loi est appelé à chaque fois qu'un acteur devrait faire un nouveau mouvement):Comment lancer et attraper une exception IllegalArgumentException?
public void act()
{
Location loc = getLocation();
if(direction==null) {
}
else if(direction.equals("NORTH")) {
Location next = loc.getAdjacentLocation(loc.NORTH);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(next);
direction = "NORTH";
}
}
else if(direction.equals("SOUTH")) {
Location next = loc.getAdjacentLocation(loc.SOUTH);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(getLocation().getAdjacentLocation(getLocation().SOUTH));
direction = "SOUTH";
}
}
else if(direction.equals("EAST")) {
Location next = loc.getAdjacentLocation(loc.EAST);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(getLocation().getAdjacentLocation(getLocation().EAST));
direction = "EAST";
}
else if(getLocation().getCol()==20 && getLocation().getRow()==9) {
moveTo(new Location(9,0));
direction = "EAST";
}
}
else if(direction.equals("WEST")) {
Location next = loc.getAdjacentLocation(loc.WEST);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
moveTo(getLocation().getAdjacentLocation(getLocation().WEST));
direction = "WEST";
}
else if(getLocation().getCol()==0 && getLocation().getRow()==9) {
moveTo(new Location(9,20));
direction = "WEST";
}
}
}
La raison du libellé bizarre dans les deux dernières Si les déclarations sont bc, je veux que le Pacman puisse se téléporter dans le vrai jeu. Maintenant, quand je lance le jeu, environ 90% du temps cela fonctionne, mais dans les 10% restants, je reçois un IllegalArgumentException bc, il dit que j'essaie de passer à un endroit qui n'est pas sur le plateau (par exemple.) et (9,21)). Je veux savoir comment je peux attraper ou jeter ou tout ce que je dois faire pour empêcher cela de se produire. Je n'ai jamais utilisé catch ou throw donc aussi s'il vous plaît essayez d'expliquer votre raisonnement merci!
Merci!J'ai donc suivi votre conseil et même si cela a pris du temps, j'ai finalement trouvé où je me trompais et j'ai fini par régler ça. –
Cool, fini avec la meilleure solution, heureux que vous l'ayez résolu! –