简体   繁体   English

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

[英]How to validate input string using while loop

I know this might seem like a simple/silly question, but I am trying to keep my code as organized and simple as possible. 我知道这似乎是一个简单/愚蠢的问题,但是我试图使我的代码尽可能有条理和简单。 The problem that I am having is with a while loop for validation. 我遇到的问题是使用while循环进行验证。 I am validating a string input. 我正在验证字符串输入。 I am using the validation simply to make sure that something is entered. 我使用验证只是为了确保输入了某些内容。 The only time I would like the while loop to run is when no information is entered at all, so I would like to include every character and symbol. 我希望运行while循环的唯一时间是根本没有输入任何信息,因此我想包含每个字符和符号。 The question that I have, is that I am wondering if there is a shorter way to include every character possible except for simply hitting enter of course. 我的问题是,我想知道是否有一种简单的方法来包含所有可能的字符,除了简单地按回车键。 Here is the simple code snippet. 这是简单的代码片段。

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);

What about restructuring it as a do-while and only having one print/scan? 如何将其重组为只做一次打印/扫描的一次打印呢?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM