首页 > 解决方案 > 使用循环确定电子邮件地址是否包含 2 个字符

问题描述

检查电子邮件地址是否有效。有效的电子邮件地址应同时包含 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);
}

标签: java

解决方案


我建议使用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 "."

推荐阅读