在JAVA中输入和验证电子邮件地址

时间:2014-11-27 15:02:40

标签: java

我已经编写了以下代码,但如果输入的输入为false,我无法循环播放。请帮助我。

System.out.println("Please enter your email address ex:xyz@gmail.com");
        String emailaddress=name.nextLine();

        String email_regex = "[A-Z]+[a-zA-Z_]+@\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
        String testString = emailaddress;
        Boolean b = testString.matches(email_regex);
        System.out.println("String: " + testString + " :Valid = " + b);
        System.out.println("Email address is " +emailaddress);

3 个答案:

答案 0 :(得分:0)

   boolean b;
   do {
        System.out.println("Please enter your email address ex:xyz@gmail.com");
        String emailaddress=name.nextLine();
        String email_regex = "[A-Z]+[a-zA-Z_]+@\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
        String testString = emailaddress;
        b = testString.matches(email_regex);
        System.out.println("String: " + testString + " :Valid = " + b);
        System.out.println("Email address is " +emailaddress);
    }while(!b);

答案 1 :(得分:0)

    String testString;
    String emailaddress;
    boolean b = false;

    do {
        System.out.println("Please enter your email address ex:xyz@gmail.com");
        Scanner name = new Scanner(System.in);
        emailaddress = name.nextLine();

        String email_regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        testString = emailaddress;
        b = testString.matches(email_regex);
        System.out.println("String: " + testString + " :Valid = " + b);
    } while (!b);

    System.out.println("Email address is " + emailaddress);

答案 2 :(得分:0)

这里有3个功能:

public class abc{

public static void main(String[] args){
   inputEmail();
}

public boolean checkEmailvalidity(String emailaddress){
    String email_regex = "[A-Z]+[a-zA-Z_]+@\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
   boolean b = testString.matches(email_regex);
   return b;
}

public void inputEmail(){
        System.out.println("Please enter your email address ex:xyz@gmail.com");
        String emailaddress=name.nextLine();
        boolean a = checkEmailvalidity(emailaddress);
       if(a){
          System.out.println("Valid email");
        } else {
          System.out.println("InValid email");
           inputEmail();
       }
}

}

这是您更新的答案:

package smsmain; 
import java.util.Scanner; 
     public class CStudentinfo { 
        public static void createstudent() { 
          Scanner name = new Scanner(System.in); 
          System.out.println("Please enter your first name:");     
             while(!name.hasNext("[a-zA-Z]+")){ 
                 System.out.println("Please re-enter your name, use alphabets)
                  System.out.println("Please enter your first name:"); 
                   name.nextLine(); 

              } 
        String firstname=name.nextLine(); 
        System.out.println("Your firstname is " + firstname); 
       inputEmail();