Java Battleship:无效输入仍然发送到下一个方法

时间:2016-07-11 15:24:33

标签: java

我写了一段代码来实现战舰游戏。 其中一个方法(pickRow)是让用户在游戏区域(5x5)中选择一行来启动。此方法检查用户输入是否在游戏板的边界内(如5x5所述),如果用户输入是一个整数(请参阅try-catch语句)。

然而,程序给出错误,因为用户输入例如是444(=无效输入)。虽然强制用户提供另一个号码,但444仍然转移到下一个方法(playerAttempt& adaptBoardAfterAttempt),引发了一个ArrayIndexOutOfBoundsException。

如何修复代码,以便无效的用户输入不再转移到后续方法?对于我的代码,请参阅下文。

谢谢, 桑德

public static int pickRow(int row) {
    //method to let the user pick a row
    //
    Scanner rowInput = new Scanner(System.in); 

    try {    //checks if user input is an integer by using try-catch statement
        System.out.print("Pick a row (1-5): "); 
        row = rowInput.nextInt();

        if (!isWithinBoundaries(row)) {    //checks if user input is within boundaries of the playing board
            System.out.println("That's outside the sea. Please provide a number from 1 to 5.");
            pickRow(row);         //asks for new user input because user input is outside boundaries of the playing board    
        } else {            
            row = row - 1;    //adjusts the value of row to correct for programming indices 
        }

    } catch (java.util.InputMismatchException e) {
        System.out.println("Sorry, invalid input. Please provide a number from 1 to 5.");
        pickRow(row);        //asks for new user input because input is not an integer 

    }              
    return row;             
}

public static int pickColumn (int column) {
    //method to let the user pick a column
    //
    Scanner columnInput = new Scanner(System.in);   

    try {    //checks if user input is an integer by using try-catch statement
        System.out.print("Pick a column (1-5): "); 
        column = columnInput.nextInt();

        if (!isWithinBoundaries(column)) {    //checks if user input is within boundaries of the playing board
            System.out.println("That's outside the sea. Please provide a number from 1 to 5.");
            pickColumn(column);         //asks for new user input because user input is outside boundaries of the playing board    
        } else {            
            column = column - 1;    //adjusts the value of column because java starts counting at 0, not 1 
        }

    } catch (java.util.InputMismatchException e) {
        System.out.println("Sorry, invalid input. Please provide a number from 1 to 5.");
        pickColumn(column);        //asks for new user input because input is not an integer   
    }              
    return column;             
}

public static void playerAttempt(int[] playerAttempt) {
    //method that incorporates player's picks of row and column into an attempt
    playerAttempt[0] = pickRow(row);
    playerAttempt[1] = pickColumn(column); 
}

public static void adaptBoardAfterAttempt (int[] playerAttempt, int[][] ships, int[][] board) {
    //adapts the playing board after a player attempt to indicate a hit (X) or a miss (0)
    if (isHit(ships,playerAttempt)) {
        board[playerAttempt[0]][playerAttempt[1]]=2;
    } else {
        board[playerAttempt[0]][playerAttempt[1]]=1;
    }
}

1 个答案:

答案 0 :(得分:0)

这对我有用(我的评论以“>>”开头):

public static int pickRow() {
        //method to let the user pick a row
        Scanner rowInput = new Scanner(System.in); 
        String response;
        int row;

        while (true) //>> loop is infinite as long as input is invalid.  As soon as it's valid, method returns, exiting the loop.
        {           
            //checks if user input is an integer by using try-catch statement
            System.out.print("Pick a row (1-5): ");
            response = rowInput.nextLine();
            try {
                row = Integer.valueOf(response);
            } catch (NumberFormatException e)
            {
                System.out.println("Sorry, invalid input. Please provide a number from 1 to 5.");
                continue;
            }

            if (!isWithinBoundaries(row))
            {    //checks if user input is within boundaries of the playing board
                System.out.println("That's outside the sea. Please provide a number from 1 to 5.");
            } else
            {                   
                row = row - 1;    //adjusts the value of row to correct for programming indices 
                return row; //>> row is valid, so return it
            }
        }
    }

以下是我改变的内容:

  • 我删除了您的论据row。它不需要是传递给方法的参数,因为Scanner检索row的值。相反,我将其声明为方法级变量。
  • 我添加了一个名为String的{​​{1}}变量。我更改了您的代码以将其检索为用户的输入,而不是response。 (即,您的row现在使用Scanner而不是nextLine()
  • 我将其余代码置于无限nextInt()循环中,并删除了递归while调用。这样,该方法只是一直要求输入,直到它最终成为有效响应,此时该方法返回行号。在任何其他实例中,响应无效并且循环继续。
  • 当我尝试将pickRow()转换为整数(以分配给NumberFormatException)时,我重新安排了异常处理以捕获response。如果抛出异常,它会再次输出错误消息和循环row

简而言之,当调用该方法时,程序会要求1 - 5.如果它太大或太小,continue会捕获它,程序会再次询问。如果它不是数字,isWithinBoundries块会捕获它,程序会再次询问。如果它是有效值,则该方法执行-1过程并返回该行。

我希望这有帮助!