Java - 我如何将字符与其他字符进行比较?
Java - How can i compare chars with other chars?
我的目标是从用户那里获得特定的输入(仅限 A、B、C 和 D)。
例如:如果我输入字母 A,if 语句将执行(它不应该)。 do while 也一样。
(逻辑错误)
char[] response = new char[20];
Scanner k = new Scanner(System.in);
//Prompts User to fill array with their responses
for(int i=0; i<response.length; i++) {
//Input validation
do {
System.out.println("Answer "+(i+1)+":");
response[i] = k.nextLine().charAt(0);
if(response[i] != 'A' ||response[i] != 'B' || response[i] != 'C' ||response[i] != 'D')
System.out.print("Try Again. ");
}
while(response[i]!= 'A' ||response[i] != 'B' ||response[i] != 'C' ||response[i] != 'D');
}
你条件倒退了。当你得到它 A 你会得到
if (false || true || true || true)
这会过去的。
将此更改为:
if(response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')
我会这样写
Scanner in = new Scanner(System.in);
char[] response = new char[20];
//Prompts User to fill array with their responses
for(int i = 0; i < response.length; i++) {
for (;;) {
System.out.println("Answer " + (i + 1) + ":");
response[i] = in.nextLine().charAt(0);
//Input validation
if ("ABCD".indexOf(response[i]) >= 0)
break;
System.out.print("Please try again, it must be A, B, C or D");
}
}
你做错的是你需要写
if (!(response[i] == 'A' || response[i] == 'B' || response[i] == 'C' || response[i] != 'D'))
或
if (response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')
我的目标是从用户那里获得特定的输入(仅限 A、B、C 和 D)。
例如:如果我输入字母 A,if 语句将执行(它不应该)。 do while 也一样。 (逻辑错误)
char[] response = new char[20];
Scanner k = new Scanner(System.in);
//Prompts User to fill array with their responses
for(int i=0; i<response.length; i++) {
//Input validation
do {
System.out.println("Answer "+(i+1)+":");
response[i] = k.nextLine().charAt(0);
if(response[i] != 'A' ||response[i] != 'B' || response[i] != 'C' ||response[i] != 'D')
System.out.print("Try Again. ");
}
while(response[i]!= 'A' ||response[i] != 'B' ||response[i] != 'C' ||response[i] != 'D');
}
你条件倒退了。当你得到它 A 你会得到
if (false || true || true || true)
这会过去的。
将此更改为:
if(response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')
我会这样写
Scanner in = new Scanner(System.in);
char[] response = new char[20];
//Prompts User to fill array with their responses
for(int i = 0; i < response.length; i++) {
for (;;) {
System.out.println("Answer " + (i + 1) + ":");
response[i] = in.nextLine().charAt(0);
//Input validation
if ("ABCD".indexOf(response[i]) >= 0)
break;
System.out.print("Please try again, it must be A, B, C or D");
}
}
你做错的是你需要写
if (!(response[i] == 'A' || response[i] == 'B' || response[i] == 'C' || response[i] != 'D'))
或
if (response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')