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

时间:2016-07-09 06:44:10

标签: java validation shortcut

我知道这可能看起来像一个简单/愚蠢的问题,但我试图让我的代码尽可能有条理和简单。我遇到的问题是使用while循环进行验证。我正在验证字符串输入。我只是使用验证来确保输入内容。我希望while循环运行的唯一时间是根本没有输入任何信息,所以我想包括每个字符和符号。我的问题是,我想知道是否有更短的方法来包括每个可能的角色,除了简单地按下输入当然。这是简单的代码片段。

Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");


System.out.print("Please enter your name: ");
String email = input.nextLine();
while(!email.matches("[a-zA-Z]+"));
{
    System.out.println("\nPlease enter a valid E-Mail.");
        email = input.nextLine();
}
out.println("E-Mail: " + email);

1 个答案:

答案 0 :(得分:3)

如何将其重组为一次,只进行一次打印/扫描?

Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");

String email;
String prompt = "Please enter your name: ";
do {
    System.out.print(prompt);
    email = input.nextLine();
    prompt = "\nPlease enter a valid E-Mail.\n"
} while (!email.matches("[a-zA-Z]+"));

out.println("E-Mail: " + email);