For this programming assignment, you have to write a Java program that tests whether a given input string represents a Valid E-mail address. If the input is not a valid e-mail address, it should print a message saying "Invalid Address". If the input is a valid e-mail address, it should print out the User name and the Domain name on separate lines. For purposes of this assignment and to keep the logic simple, a valid E-mail address will be of the form

Respuesta :

Answer:

To check if the email address is correct it should have only one "@" symbol, we have to split the input string by this symbol. The code in java to achieve this is the following:

class Main {

 public static void main(String[] args) {

   String email = "prueba@tprueba";

   String[] email_split = email.split("@");

   long count_a = email.chars().filter(ch -> ch == '@').count();

   if(count_a == 1){

     System.out.println("User name:   "+email_split[0]);

     System.out.println("Domain name: "+email_split[1]);

   }else{

     System.out.println("There is no valid email address.");

   }

 }

}

Explanation:

The explanation of the code is given below:

class Main {

 public static void main(String[] args) {

   String email = "prueba@prueba"; //input string to evaluate if is valid email

   long count_a = email.chars().filter(ch -> ch == '@').count(); //Count how many times the symbol @ appears

   if(count_a == 1){ //A valid email only contains one at

     String[] email_split = email.split("@"); //separate the values using the at in an array

     System.out.println("User name:   "+email_split[0]); //the first element is the username

     System.out.println("Domain name: "+email_split[1]); //the second element is the domain name

   }else{

     System.out.println("There is no valid email address."); //If there isn´t an at or are more than one then display a message saying the email is not valid

   }

 }

}