我正在做一个非常基本的战舰游戏。与真实物体不同,该程序会生成0到6之间的三个随机整数。然后,玩家必须通过输入整数来猜测飞船的位置。
因此,现在的程序是:
public class digitBattleShips {
static int choice;
int playerScore;
int shipLoc1;
int shipLoc2;
int shipLoc3;
Random rand = new Random();
static Scanner input = new Scanner(System.in);
public void digitBattleShipsGame() {
shipLoc1 = rand.nextInt(7);
shipLoc2 = rand.nextInt(7);
shipLoc3 = rand.nextInt(7);
System.out.println(
"Welcome to digit BattleShips! In this game, you will choose a
number from 0 to 6. There are 3 ships to destroy, if you get them
all, you win");
while (playerScore != 3) {
System.out.println("Choose a number from 0 to 6");
playerChoice();
if (choice == shipLoc1 || choice == shipLoc2 || choice == shipLoc3) {
System.out.println("KABOOOOOOM!");
playerScore++;
} else {
System.out.println("Sploooosh...");
}
}
System.out.println("HURRRAAAAAAY you win");
}
public static void playerChoice() {
try {
choice = (int) input.nextInt();
while (choice<0 || choice>6) {
System.out.println("Error. You have to choose a number from 0 to 6");
playerChoice();
} }
catch (InputMismatchException ex) {
System.out.println("Invalid input! You have to enter a number");
playerChoice();
}
}
public static void main(String[] args) {
digitBattleShips digit = new digitBattleShips();
digit.digitBattleShipsGame();
}
}
目前,这是发生的情况:
1)如果玩家选择0到6之间的整数,则while循环会按预期工作,并将持续到玩家击中shipLoc1,shipLoc2和shipLoc3代表的三艘飞船为止
2)如果玩家选择大于或小于0和6的数字,则会显示错误,并再次提示玩家进行其他输入。如预期的那样在这里工作。
3)如果玩家选择了字符,字符串,浮点数等,则抛出异常,但不允许玩家再次更改其输入。
我认为创建一个专门设计的方法(在代码中命名为playerChoice())以允许输入进行排序,因此,在引发异常之后,此方法会再次激活,以便玩家可以选择另一个数字。但是,从我的有限理解来看,它确实看起来像是存储了无效选择,因此,当调用此方法时,由于无效选择始终存在,因此会自动再次引发异常。然后,这将创建一个引发异常的无限循环。
这个想法是允许在另一个输入无效之前允许另一个输入,即不是整数,以便3)以与2)相同的方式进行操作。
我认为我在这里面临的困惑可能是由于我如何放置while和try / catch技术。请提供一些指导以及如何防止3)发生
交互式爱情
慕的地8271018
相关分类