使用 while 循环验证字符串输入



我在这个简单的代码上遇到了非常困难的时期。我的 while 条件始终被忽略,打印语句被执行。请帮忙。

package Checkpoints;
import java.util.Scanner;

public class Check05 {
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
/**
* Write an input validation that asks the user to enter 'Y', 'y', 'N', or 'n'.
*/

String input, Y = null, N = null;
System.out.println("Please enter the letter 'Y' or 'N'.");
input = keyboard.nextLine();

while (!input.equalsIgnoreCase(Y) || !(input.equals(N)))
//|| input !=y || input !=N ||input !=n)
{
System.out.println("This isn't a valid entry. Please enter the letters Y or N" );
input = keyboard.nextLine();
}
}
}

更改此设置;

String input, Y = null, N = null;

对此;

String input, Y = "Y", N = "N";

以便您可以将用户输入字符串与"Y"和"N"字符串进行比较。

而这个;

while (!input.equalsIgnoreCase(Y) || !(input.equals(N)))

对此;

while (!(input.equalsIgnoreCase(Y) || input.equalsIgnoreCase(N)))

因为你的条件设计是错误的,正如@talex警告的那样。

您正在将输入与null进行比较,因为您忘记定义字符串YN的值。

您可以在常量中定义答案值,如下所示:

public static final String YES = "y";
public static final String NO  = "n";
public static void main (String[] args) {
Scanner keyboard;
String  input;
keyboard = new Scanner(System.in);
System.out.println("Please enter the letter 'Y' or 'N'.");
input = keyboard.nextLine();
while (!(input.equalsIgnoreCase(YES) || input.equalsIgnoreCase(NO))) {
System.out.println("This isn't a valid entry. Please enter the letters Y or N" );
input = keyboard.nextLine();
}
}

编辑:根据talex的建议更正了while条件

在"while"循环之前添加这个额外的条件以避免这种情况

if(Y!= null && !Y.isEmpty()) 
if(N!= null && !N.isEmpty())

最新更新