在 Java 中,我试图通过检查无效输入来验证输入。不知何故它没有正确返回错误
In Java, I am trying to validate input by checking for invalid input. Somehow it is not correctly returning an error
首先,让我简要介绍一下我正在尝试做的事情。对于大学作业,我必须在 Java 中重新创建游戏 Mastermind。到目前为止一切都进展顺利,直到我到了验证用户输入的特定点。我有一个名为 colorList 的字符串数组,这个列表由字母 A 到 F 填充(这些是颜色的副标题。)
当用户进行猜测时,他输入一个4个字母的代码,例如ABCD。我要确定的是,猜测中的每个字符也包含在colorList数组中,以防止用户猜测不存在的'colors'。
我用来验证这一点的代码如下:
boolean incorrectInput = true;
while (incorrectInput) {
boolean ooitgoed = false;
outerloop: for (int a = 0; a < code.length(); a++) { // Select next letter in input.
for (int i = 0; i < colorList.size(); i++) { // Select next element in array to compare to.
ooitgoed = false; // Will put the boolean on false for as long as it does not find the selected char in the array.
if (colorList.get(i).charAt(0) == code.charAt(a)) { // If selected input character is equal to selected element from array:
System.out.println("Code char: " + code.charAt(a) + " - " + "Element from array: " + colorList.get(i) + " - correct input");
ooitgoed = true;
incorrectInput = false;
break; // Break out of the for-loop, which causes the next character of the input to be selected and then compared to every element in the array.
}
}
if (ooitgoed == false) { // If the selected char is never found in the array, the boolean will still be false and a new input will be requested.
System.out.println("Found incorrect input! Please only use 'A', 'B', 'C', 'D', 'E', or 'F'.");
System.out.println("Enter your guess: ");
input = in.next();
input = input.toUpperCase();
incorrectInput = true;
break outerloop; // Break back to outerloop, re-executing the entire validation process with the new input requested above.
}
}
}
我在代码中添加了一些注释来解释几个应该工作的过程,但我找不到它为什么不工作的原因。
我执行程序并进行猜测时得到的输出如下:
Code = DCFF
Enter your guess:
DCFU
Code char: D - Element from array: D - correct input
Code char: C - Element from array: C - correct input
Code char: F - Element from array: F - correct input
Code char: F - Element from array: F - correct input
U 应该被发现为无效输入,但程序以某种方式认为它是 F 并继续对其进行验证。
我在代码中添加了一些注释来解释几个应该工作的过程,但我找不到它为什么不工作的原因。
如果您需要有关我的代码的更多信息,请告诉我,我会尽可能多地提供给您。我希望任何人都能弄清楚。
谢谢!
您正在 incorrectInput
循环中测试来自 code
的字符。应该是input
。
还有一些关于您的代码的评论:
你不需要ooitdoed
和incorrectInput
,任何一个都足以满足你的条件。
outerloop
实际上是内部的 :) 而且您不需要那个标签 - 只需 break
,没有标签就可以了。
不要像 if (ooitgoed == false)
这样写布尔检查 - 只是 if(!ootitgoed)
如果将 colorList
设为字符串 "ABCDEF" 而不是数组,并将最内层的循环替换为 incorrectInput = colorList.indexOf(input.charAt(a)) == -1
您还可以一次验证整个字符串,而无需使用正则表达式的任何过程循环:incorrectInput = !input.toUpperCase.matches("[A-F]+")
。或者,如果您还想报告哪个字符错误:
Pattern p = Pattern.compile("[^A-F]", Pattern.CASE_INSENSITIVE); // Do this before all loops
// ...
Matcher m = p.matcher(input);
incorrectInput = m.find();
if(incorrectInput) System.out.println("This symbol is invalid: " + m.group());
这是一种更快捷的方式来完成您想要的事情:
private static final char[] COLORS = {'A', 'B', 'C', 'D', 'E', 'F'};
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
boolean inputOk;
do {
inputOk = true;
// read the input
System.out.print("Enter your guess: ");
input = br.readLine().toUpperCase();
// do the check
for (int i = 0; i < input.length() && inputOk; i++) {
for (int j = 0; j < COLORS.length; j++) {
if (input.charAt(i) == COLORS[j])
break;
if (j == COLORS.length - 1)
inputOk = false;
}
}
// input isn't ok
if (!inputOk)
System.out.println("Found incorrect input! Please only use 'A', 'B', 'C', 'D', 'E', or 'F'.");
} while (!inputOk);
}
首先,让我们创建一个方法来验证 characters
。我们称它为 isCharValid
:
public boolean isCharValid(char ch, List<String> list) {
for (String s : list) {
if (s.charAt(0) == ch) {
return true;
}
}
return false;
}
现在,将您的代码更改为:
while (true) {
String input = in.next().toUpperCase();
boolean validated = true;
for (char ch : input.toCharArray()) {
if (!isCharValid(ch, YOUR_COLOR_LIST)) {
validated = false;
break;
}
}
if (validated) {
// The input is OK!
}
else {
System.out.println("Invalid output. Please, try again.");
// Now it will go back to the beginning of the while-loop.
}
}
通用指针:利用List
s。
final List<Character> allowedInputs = new ArrayList<>();
allowedInputs.add('A');
allowedInputs.add('B');
allowedInputs.add('C');
allowedInputs.add('D');
final String input = getInput(); //gets the input from the user..
final char[] inputChars = input.toCharArray();
for (final char inputChar : inputChars) {
if (allowedInputs.contains(inputChar)) {
//All good
} else {
//Error in input!
}
首先,让我简要介绍一下我正在尝试做的事情。对于大学作业,我必须在 Java 中重新创建游戏 Mastermind。到目前为止一切都进展顺利,直到我到了验证用户输入的特定点。我有一个名为 colorList 的字符串数组,这个列表由字母 A 到 F 填充(这些是颜色的副标题。)
当用户进行猜测时,他输入一个4个字母的代码,例如ABCD。我要确定的是,猜测中的每个字符也包含在colorList数组中,以防止用户猜测不存在的'colors'。
我用来验证这一点的代码如下:
boolean incorrectInput = true;
while (incorrectInput) {
boolean ooitgoed = false;
outerloop: for (int a = 0; a < code.length(); a++) { // Select next letter in input.
for (int i = 0; i < colorList.size(); i++) { // Select next element in array to compare to.
ooitgoed = false; // Will put the boolean on false for as long as it does not find the selected char in the array.
if (colorList.get(i).charAt(0) == code.charAt(a)) { // If selected input character is equal to selected element from array:
System.out.println("Code char: " + code.charAt(a) + " - " + "Element from array: " + colorList.get(i) + " - correct input");
ooitgoed = true;
incorrectInput = false;
break; // Break out of the for-loop, which causes the next character of the input to be selected and then compared to every element in the array.
}
}
if (ooitgoed == false) { // If the selected char is never found in the array, the boolean will still be false and a new input will be requested.
System.out.println("Found incorrect input! Please only use 'A', 'B', 'C', 'D', 'E', or 'F'.");
System.out.println("Enter your guess: ");
input = in.next();
input = input.toUpperCase();
incorrectInput = true;
break outerloop; // Break back to outerloop, re-executing the entire validation process with the new input requested above.
}
}
}
我在代码中添加了一些注释来解释几个应该工作的过程,但我找不到它为什么不工作的原因。
我执行程序并进行猜测时得到的输出如下:
Code = DCFF
Enter your guess: DCFU
Code char: D - Element from array: D - correct input
Code char: C - Element from array: C - correct input
Code char: F - Element from array: F - correct input
Code char: F - Element from array: F - correct input
U 应该被发现为无效输入,但程序以某种方式认为它是 F 并继续对其进行验证。
我在代码中添加了一些注释来解释几个应该工作的过程,但我找不到它为什么不工作的原因。
如果您需要有关我的代码的更多信息,请告诉我,我会尽可能多地提供给您。我希望任何人都能弄清楚。
谢谢!
您正在 incorrectInput
循环中测试来自 code
的字符。应该是input
。
还有一些关于您的代码的评论:
你不需要
ooitdoed
和incorrectInput
,任何一个都足以满足你的条件。outerloop
实际上是内部的 :) 而且您不需要那个标签 - 只需break
,没有标签就可以了。不要像
if (ooitgoed == false)
这样写布尔检查 - 只是if(!ootitgoed)
如果将
colorList
设为字符串 "ABCDEF" 而不是数组,并将最内层的循环替换为incorrectInput = colorList.indexOf(input.charAt(a)) == -1
您还可以一次验证整个字符串,而无需使用正则表达式的任何过程循环:
incorrectInput = !input.toUpperCase.matches("[A-F]+")
。或者,如果您还想报告哪个字符错误:Pattern p = Pattern.compile("[^A-F]", Pattern.CASE_INSENSITIVE); // Do this before all loops // ... Matcher m = p.matcher(input); incorrectInput = m.find(); if(incorrectInput) System.out.println("This symbol is invalid: " + m.group());
这是一种更快捷的方式来完成您想要的事情:
private static final char[] COLORS = {'A', 'B', 'C', 'D', 'E', 'F'};
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
boolean inputOk;
do {
inputOk = true;
// read the input
System.out.print("Enter your guess: ");
input = br.readLine().toUpperCase();
// do the check
for (int i = 0; i < input.length() && inputOk; i++) {
for (int j = 0; j < COLORS.length; j++) {
if (input.charAt(i) == COLORS[j])
break;
if (j == COLORS.length - 1)
inputOk = false;
}
}
// input isn't ok
if (!inputOk)
System.out.println("Found incorrect input! Please only use 'A', 'B', 'C', 'D', 'E', or 'F'.");
} while (!inputOk);
}
首先,让我们创建一个方法来验证 characters
。我们称它为 isCharValid
:
public boolean isCharValid(char ch, List<String> list) {
for (String s : list) {
if (s.charAt(0) == ch) {
return true;
}
}
return false;
}
现在,将您的代码更改为:
while (true) {
String input = in.next().toUpperCase();
boolean validated = true;
for (char ch : input.toCharArray()) {
if (!isCharValid(ch, YOUR_COLOR_LIST)) {
validated = false;
break;
}
}
if (validated) {
// The input is OK!
}
else {
System.out.println("Invalid output. Please, try again.");
// Now it will go back to the beginning of the while-loop.
}
}
通用指针:利用List
s。
final List<Character> allowedInputs = new ArrayList<>();
allowedInputs.add('A');
allowedInputs.add('B');
allowedInputs.add('C');
allowedInputs.add('D');
final String input = getInput(); //gets the input from the user..
final char[] inputChars = input.toCharArray();
for (final char inputChar : inputChars) {
if (allowedInputs.contains(inputChar)) {
//All good
} else {
//Error in input!
}