使用循环确定电子邮件地址是否包含 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);

}


慕村225694
浏览 135回答 2
2回答

冉冉说

我建议使用while循环。当for您知道需要重复操作多少次时,循环是最好的,但while循环适用于重复未知次数。它可以运行 0 到多次。至于您的while循环条件,您只想检查电子邮件地址是否无效。因此,请检查!emailAddress.contains("@")它是否不包含@,!emailAddress.contains(".")如果不包含.。您可以使用||来查看任一条件是否为真。// Prompt the userSystem.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 "."

喵喔喔

像这样的东西应该工作:// While email does not contain the two characters..// Keep asking the user to enter the correct email.while(!emailAddress.contains("@") || !emailAddress.contains(".")){     System.out.print("\nYou have entered an invalid email address.");    // Add line of code here to ask for email address.    // Update emailAddress of course}//prompt user for major & classification codeSystem.out.print("\nPleast enter two characters (Character #1: Major Code and Character #2: Classification // ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java