gpt4 book ai didi

java - 我如何才能无异常(exception)地修复此逻辑语句错误?

转载 作者:行者123 更新时间:2023-11-30 01:51:08 24 4
gpt4 key购买 nike

介绍

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

问题

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

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

因此,如果用户输入的数字小于0或大于(size-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!");是调试标准输出。

最佳答案

意见建议:


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

人们确实会犯输入错误,而您的应用程序提供的信息越丰富,用户犯的错误就越少。例如,如果您只希望用户输入一个从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)用于保存用户提供的值。这使我们可以使用嵌套在主播放while循环中的单个for循环来提示用户的所有4个输入,因此可以消除一些重复的代码并可以在一间屋子中进行输入验证。

如果要将输入转换为Integer(int's),则可以改为执行以下操作(直接在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列不能大于(size-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;
}


是的...这一切都可以减少更多。

关于java - 我如何才能无异常(exception)地修复此逻辑语句错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55991676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com