检查电子邮件地址是否有效。有效的电子邮件地址应包含 at 符号 (@) 或点 (.)。如果用户省略 或者,您的程序必须通知用户提供的电子邮件不正确并提示 用户重新输入电子邮件地址。继续重复此步骤,直到用户提供有效的电子邮件 地址。当用户输入有效的电子邮件地址后,继续程序的其余部分。 - 我们应该为此使用循环,但我不确定使用哪个或如何设置它。我正在考虑使用 while 循环?我们不能使用我在这里看到人们使用的正则表达式方法,因为我们还没有了解到这一点。
This is the code that we have to update
(we are now supposed to use a loop to continue asking the user
for email address until both characters are used,
instead of exiting the program):
if(emailAddress.contains("@")){
//prompt user for major & classification code
System.out.print("\nPleast enter two characters (Character #1: Major Code and Character #2: Classification Code): ");
}
else{
//exit program if no '@' symbol in email address
System.out.print("\nYou have entered an invalid email address.");
System.out.println("\n\nGoodbye!");
System.exit(0);
}
最佳答案
我建议使用 while
循环。当您知道需要重复操作多少次时,for
循环是最好的选择,而 while
循环则适合重复未知次数。它可以运行 0 到多次。
至于 while
循环的条件,您只想检查电子邮件地址是否无效。因此,请检查 !emailAddress.contains("@")
看看它是否不包含 @
、!emailAddress.contains(".")
如果不包含 .
。
您可以使用 ||
来查看任一条件是否为真。
// Prompt the user
System.out.println("Please enter an email address");
String emailAddress = // read in their email adress
while(!emailAddress.contains("@") || !emailAddress.contains(".")) {
System.out.println("You have entered an invalid email address, please enter another.");
emailAddress = // read in their email address again
}
// Email address now contains "@" and "."
关于java - 使用循环确定电子邮件地址是否包含 2 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55753217/