检查电子邮件地址是否有效。有效的电子邮件地址应同时包含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);
}
答案 0 :(得分:2)
我建议使用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 "."
答案 1 :(得分:0)
类似的事情应该起作用:
// 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 code
System.out.print("\nPleast enter two characters (Character #1: Major Code and Character #2: Classification
// ...