我如何才能无例外地修复此逻辑语句错误?

时间:2019-05-05 11:58:29

标签: java logic

简介

我现在要提供的代码是游戏循环的一部分。我在处理错误(不是通过异常)时遇到问题。

问题

此下一个函数采用4个int变量(row_1, col_1, row_2, col_2),如果它们小于(size-1),则必须检查它们。

背后的原因是我们正在处理矩阵,范围为from 0 to (size-1)

因此,如果用户输入的数字小于0或大于(大小1),则应该再次要求输入

代码

 public static void gameLoop()
{
    //While you still play (true) or if (false) -> end game
    showMatrix(gameMatrix);//Cheat
    while(play == true)
        {
            showMatrix(displayMatrix);
            System.out.println("--------------------");
            System.out.println("Input first row and col press enter between inputs");
            System.out.print("First row: ");
                row_1 = scan.nextInt();
            System.out.print("First column: ");
                col_1 = scan.nextInt();
            System.out.println("Input second row and col press enter between inputs");
            System.out.print("Second row: ");
                row_2 = scan.nextInt();
            System.out.print("Second column: ");
                col_2 = scan.nextInt();

                if (row_1 == row_2 && col_1 == col_2)
                {
                    System.out.println("I tested this!");
                    showMatrix(displayMatrix);
                    System.out.println("--------------------");
                    System.out.println("[ERROR] Input not valid! Try again");
                    System.out.println("Input first row and col press enter between inputs");
                    System.out.print("First row: ");
                        row_1 = scan.nextInt();
                    System.out.print("First column: ");
                        col_1 = scan.nextInt();
                    System.out.println("Input second row and col press enter between inputs");
                    System.out.print("Second row: ");
                        row_2 = scan.nextInt();
                    System.out.print("Second column: ");
                        col_2 = scan.nextInt();
                }
                else if ((row_1 > size || row_1 < 0) && (row_2 > size || row_2 < 0) && (col_1 > size || col_2 < 0) && ((col_2 > size || col_2 < 0)))     
                {
                    System.out.println("I tested that!");
                    showMatrix(displayMatrix);
                    System.out.println("--------------------");
                    System.out.println("[ERROR] Input not valid! Try again");
                    System.out.println("Input first row and col press enter between inputs");
                    System.out.print("First row: ");
                        row_1 = scan.nextInt();
                    System.out.print("First column: ");
                        col_1 = scan.nextInt();
                    System.out.println("Input second row and col press enter between inputs");
                    System.out.print("Second row: ");
                        row_2 = scan.nextInt();
                    System.out.print("Second column: ");
                        col_2 = scan.nextInt();
                }


            Turn(row_1, col_1, row_2, col_2, gameMatrix);
            check = checkEndgame(gameMatrix, displayMatrix);

                if(check == false)
                {
                    System.out.println("Would you like to play again? Y/N");
                        game_option = scan.next();

                        if ("Y".equals(game_option) || "y".equals(game_option))
                        {
                            createGame();
                            gameLoop();
                        }     
                        else if ("N".equals(game_option) || "n".equals(game_option))
                        {
                            play = false;
                        }
                }


        }
}

部分代码出现问题

if (row_1 == row_2 && col_1 == col_2){}

else if ((row_1 > size || row_1 < 0) && (row_2 > size || row_2 < 0) && (col_1 > size || col_2 < 0) && ((col_2 > size || col_2 < 0))){}

问题

在测试应该触发它的数字之后,我不知道我在哪里犯了这个逻辑。

注释

  • 随时判断代码并帮助我进行设计或错误处理
  • 这些System.out.println("I tested that!"); && System.out.println("I tested this!");是调试标准输出。

2 个答案:

答案 0 :(得分:1)

您应该使用do...while循环来确保输入有效。它需要一个boolean参数:

do {
    // All the System.out.println and Scanner stuff...
} while(!checkAnswers(row_1, row_2, col_1, col_2));

现在,我们必须编写函数checkAnswers,该函数将返回布尔值以说明是否允许用户退出do...while循环:

public static boolean checkAnswers(int row_1, int row_2, int col_1, int col_2) {
    // I don't know why you needed that condition, but I let it there
    if(row_1 == row_2 || col_1 == col_2) return false; 

    // check if the rows and colls are in the range 0...(size - 1)
    int[] rowsAndCols = {row_1, row_2, col_1, col_2};
    for(int i : rowsAndCols)
        if(i < 0 || i >= (size - 1)) return false;

    // If everything is good we can quit the do...while loop
    return true;
}

答案 1 :(得分:1)

  

建议:

控制台应用程序是不可原谅的,除非在开发阶段进行仔细处理会导致应用程序无人使用,因为它无法处理输入错误或简单的键入错误。您愿意重启应用多少次。

人们的确会犯输入错误,而您的应用程序提供的信息越丰富,用户犯的错误就越少。例如,如果您只希望用户输入一个从0到10的值,那么让他们不断知道要求是什么:

Please enter the numerical values for FIRST Row and Column:
First Row (0 to 10): 7
First Column (0 to 10): |

您将始终需要验证输入,以确保所提供的内容将在不产生任何错误的情况下进行实际处理。如您所知,键盘是一个很大的输入设备,上面有很多按钮,并且在输入过程中可能会意外敲击其中的任何一个,而用户甚至没有意识到。毕竟,拥有键盘的每个人都是自动打字大师,每分钟可以输出400个单词,而无需查看屏幕。好吧....所以看起来并且说实话,我绝不例外。

如果出现错误,则允许用户重新输入。不要害怕为此利用 while 循环,甚至是嵌套循环。如果处理正确,则不会有任何问题。

尽管您的应用程序的这一部分很小,但请允许用户随时退出,除非当然要完成当前点 以完成清理工作出口。除非您不完成应用程序,否则这很讨厌。尤其是当您不想这么做的时候。

在可能的情况下,使用方法或类减少或消除代码重复。有时,冗长且重复很多的代码很容易阅读,但在大多数情况下,花很长时间就不会感到厌倦。一段时间后它会使您头晕。原来的借口“我只是要做它,然后我将其清理干净”实际上并没有奏效,大部分情况下都是如此。如果您可以立即消除代码重复,则不必编写应用程序两次或三次或更多。是的,我们都以一种或另一种形式来做,我也不例外。

通过删除大多数代码重复并添加一两个小的方法,您的特定代码段可能看起来像这样:

Scanner scan = new Scanner(System.in);      // Declare Scanner (here for sake of this demo)
String LS = System.lineSeparator();         // System line Separator. 
boolean play = true;                        // Play flag
int size = 8;                               // 8 is used for sake of this demo
String range = "(0 to " + (size - 1) + ")"; // Range so we don't have to keep typing it.
String[] rowCol;                            // Array to hold Row and Column string numerical values
String border1 = String.join("", Collections.nCopies(72, "-")); // Text Border 1 (-)
String border2 = String.join("", Collections.nCopies(42, "=")); // Text Border 2 (=)

while (play) {
    String input = "";  // Input from scanner goes in this variable
    rowCol = new String[4]; // Initialize Array
    // Declare & init int variables to hold input integer values (if desired)
    // Un-comment the below line if you want this...
    // int row_1 = -1, col_1 = -1, row_2 = -1, col_2 = -1; 

    // Inform of what is required...
    System.out.println(border1);
    System.out.println("Please enter the numerical values for FIRST and "
            + "SECOND Rows and Columns." + LS + "Follow the provided prompts. "
            + "You can Enter 'q' or 'quit' at any time to" + LS + "end the game.");
    System.out.println(border1);

    // Get Input from User
    for (int i = 0; i < rowCol.length; i++) {
        // Set up current prompt...
        String prompt = LS;
        switch (i) {
            case 0:
                prompt += "Enter First Row Value " + range + ": ";
                break;
            case 1:
                prompt += "Enter First Column Value " + range + ": ";
                break;
            case 2:
                prompt += "Enter Secomd Row Value " + range + ": ";
                break;
            case 3:
                prompt += "Enter Second Column Value " + range + ": ";
                break;
        }

        input = "";     // Clear input variable
        // Get the actual input from User and validate.
        while (input.equals("")) {
            System.out.print(prompt);       // Display prompt
            input = scan.nextLine();        // Get keyboard input from User

            // Validate input...
            if (!validateUserRowColInput(0, (size - 1), input)) {
                input = ""; // Input was invalid so clear input variable
                continue;   // Re-prompt the User for proper input
            }
            rowCol[i] = input;  // All is good so add input to Array element at index i.
        }
    }

    // Display what was provided.
    System.out.println(border2);
    System.out.println("Row 1/Column 1  = " + rowCol[0] + "/" + rowCol[1] + LS
            + "Row 2/Column 2  = " + rowCol[2] + "/" + rowCol[3]);
    System.out.println(border2 + LS);
}

您可以添加自己的其余游戏循环代码。在上面的代码中,一个简单的字符串数组(名为 rowCol )用于保存用户提供的值。这使我们可以使用嵌套在主播放内的单个 for 循环,而循环提示用户输入所有4个输入,因此消除了重复的代码并进行了所有输入验证在一个房子里可以这么说。

如果要将输入转换为Integer(整数),则可以改成这样的方法(直接在 for 循环之后):

/* Array index 0 and 1 now contains the string numerical 
   values for First Row and First Column. Array index 2 and
   3 now contains the string numerical values for Second Row 
   and Second Column. If you just can't wrap your head around 
   dealing with Arrays and indexes from this point then do 
   something like the following:     */

// Convert String Array elements to integers
row_1 = Integer.parseInt(rowCol[0]);
col_1 = Integer.parseInt(rowCol[1]);
row_2 = Integer.parseInt(rowCol[2]);
col_2 = Integer.parseInt(rowCol[3]);

// Display what was provided.
System.out.println(border2);
System.out.println("Row 1/Column 1  = " + row_1 + "/" + col_1 + LS
        + "Row 2/Column 2  = " + row_2 + "/" + col_2);
System.out.println(border2 + LS);

validateUserRowColInput()方法隐含地验证了用户输入,以遵守上述代码段的所需规则。用户提供输入后直接调用它。验证规则基本上就是您在帖子中制定的规则,验证是在提供的每个输入上完成的,而不是等待所有四个输入都提供:

验证规则:

  • 不允许空白条目;
  • 只能提供数字字符,不能提供其他字母字符 大于 q 或单词 quit (不区分大小写);
  • 如果提供了 q 或单词 quit ,则程序结束;
  • 第1行或第2行不能小于0;
  • 第1列和/或第2列不能小于0;
  • 第1行和/或第2行不能大于(大小-1);
  • 第1列和/或第2列不能大于(大小-1);

当然会通知用户是否违反规则,并有机会进行正确的输入。这是 validateUserRowColInput()方法:

/**
 * Validates the User's Row and Column values input. This method checks to
 * ensure only numerical characters were entered. It also ensures the the
 * numerical value entered is between and or equal to the supplied minValue
 * and maxValue.
 *
 * @param minVal      (Integer) The minium Allowable integer value to be
 *                    entered.
 * @param maxVal      (Integer) The maximum allowable integer value to be
 *                    entered.
 * @param inputString (String) String representation of the integer value
 *                    supplied.
 *
 * @return (Boolean) True if the entry is valid and false if it is not.
 */
private static boolean validateUserRowColInput(int minVal, int maxVal, String inputString) {
    String LS = System.lineSeparator();
    if (inputString.equals("")) {
        System.out.println("Invalid Entry! You must supply a numerical "
                + "value from " + minVal + " to " + maxVal + ".");
        return false;
    }
    if (inputString.equalsIgnoreCase("q") || inputString.equalsIgnoreCase("quit")) {
        System.out.println("We hope you had fun. Bye Bye");
        System.exit(0);
    }
    if (!inputString.matches("\\d+")) {
        System.out.println("Invalid input supplied (" + inputString + ")! "
                + "You can not supply alpha characters, only" + LS 
                + "numerical values are allowed!. Please try again...");
        return false;
    }
    int num = Integer.parseInt(inputString);
    if (num < minVal || num > maxVal) {
        System.out.println("Invalid input supplied (" + inputString + ")! "
                + "The numerical value you supply can not be" + LS + "less "
                + "than " + minVal + " and no greater than " + maxVal + ". "
                + "Please try again...");
        return false;
    }
    return true;
}

是的。...所有这些都可以减少更多。