Java 如果用户输入不是整数,并且允许用户提供另一个输入,如何确保引发异常?

Java 如果用户输入不是整数,并且允许用户提供另一个输入,如何确保引发异常?,java,exception,while-loop,java.util.scanner,Java,Exception,While Loop,Java.util.scanner,我正在做一个非常基本的战舰游戏。与实际情况不同,该程序生成三个从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(

我正在做一个非常基本的战舰游戏。与实际情况不同,该程序生成三个从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();
}
公共级数字战舰{
静态整数选择;
int playerScore;
int shipLoc1;
int shipLoc2;
int shipLoc3;
Random rand=新的Random();
静态扫描仪输入=新扫描仪(System.in);
公共无效数字战列舰名称(){
shipLoc1=兰特·耐克斯汀(7);
shipLoc2=兰特·耐克斯汀(7);
shipLoc3=兰特·耐克斯汀(7);
System.out.println(
“欢迎来到数字战舰!在这个游戏中,你将选择一个
从0到6的数字。如果你得到了3艘飞船,就要摧毁它们
好吧,你赢了);
while(playerScore!=3){
System.out.println(“从0到6中选择一个数字”);
playerChoice();
if(choice==shipLoc1 | | choice==shipLoc2 | | choice==shipLoc3){
System.out.println(“kabooooom!”);
playerScore++;
}否则{
System.out.println(“splooosh…”);
}
}
System.out.println(“你赢了吗”);
}
公共静态无效播放器选择(){
试一试{
choice=(int)input.nextInt();
while(选项6){
System.out.println(“错误。您必须从0到6中选择一个数字”);
playerChoice();
} }
捕获(输入不匹配异常){
System.out.println(“输入无效!必须输入一个数字”);
playerChoice();
}
}
公共静态void main(字符串[]args){
数字战列舰数字=新的数字战列舰();
digit.digittbattleshipsgame();
}
}

目前,情况是这样的:

1)如果玩家选择0到6之间的整数,while循环将按预期工作,并将继续,直到玩家击中由shipLoc1、shipLoc2和shipLoc3表示的三艘船

2)如果播放机选择的数字高于或低于0和6,则会显示错误,并再次提示播放机进行其他输入。按这里的计划工作

3)如果玩家选择了字符、字符串、浮点数等,则会抛出异常,但不允许玩家再次更改其输入

我认为创建一个专门设计的方法(在代码中命名为playerChoice())来允许输入可以解决这个问题,因此,在抛出异常后,这个方法会再次激活,以便玩家可以选择另一个数字。然而,从我有限的理解来看,它看起来确实像是存储了无效的选择,因此,当调用此方法时,当无效的选择始终保留时,会自动再次抛出异常。然后,这将创建一个抛出异常的无限循环

如果之前的输入无效,即不是整数,则允许另一个输入,因此3)的操作方式与2)相同


我认为我在这里面临的困惑可能是由于我如何放置while和try/catch技术。请提供一些指导,以及如何防止3)在谷歌搜索一点后发生。在抛出异常后,输入似乎没有被清除(请参阅)

因此,由于您没有调用“input.next();”,它会不断读取相同的输入,意识到它不是整数并引发异常

解决方案:

 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");
    input.next();
    playerChoice();
}
试试看{
choice=(int)input.nextInt();
while(选项6){
System.out.println(“错误。您必须从0到6中选择一个数字”);
playerChoice();
} }
捕获(输入不匹配异常){
System.out.println(“输入无效!必须输入一个数字”);
input.next();
playerChoice();
}

这就是我要做的:

public static void playerChoice()
{
    try
    {
        String inStr = input.nextLine();
        int inInt = Integer.parseInt(inStr); // throws exception.
        if (inInt < 0 || inInt > 6) // If number out of range, try again.
        {
            System.out.println("Error. You have to choose a number from 0 to 6");
            playerChoice();
        }
        else
        {
            choice = inInt;
        }
    }
    catch (NumberFormatException ex) // If exception, try again.
    {
        System.out.println("Invalid input! You have to enter a number");
        playerChoice();
    }
}
publicstaticvoidplayerchoice()
{
尝试
{
String inStr=input.nextLine();
int-inInt=Integer.parseInt(inStr);//引发异常。
如果(inInt<0 | | inInt>6)//如果数字超出范围,请重试。
{
System.out.println(“错误。您必须从0到6中选择一个数字”);
playerChoice();
}
其他的
{
选择=inInt;
}
}
catch(NumberFormatException ex)//如果出现异常,请重试。
{
System.out.println(“输入无效!必须输入一个数字”);
playerChoice();
}
}

我不依赖于
Scanner.nextInt()
,而是首先将输入读取为字符串(因为这一步不涉及解析),然后使用
Integer.parseInt()
手动解析。将读取/获取与转换/解析分离通常是一种很好的做法。

是的,简单的调整是有意义的,因为它“清除”了以前的输入!非常感谢你这么快的回复和优雅的解释。我是新来的,非常感谢!我还使用了input.next(),效果很好。我认为在这个特定的程序中使用哪一个并不重要,但如果事情更复杂,这有关系吗?input.next()实际上更正确,因为nextLine搜索换行符并读取输入,直到找到一个为止。我将更新我的答案(见)@ Zoo201如果这个答案解决了你的问题,那么你可能会考虑接受它。是的,还有另一个答案,这也是有洞察力的,所以谢谢你的两个其他用户。有什么地方你可以接受答案吗?还是你只是说说而已?如果是后者,我当然接受答案