78.9k views
2 votes
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

User Jvdneste
by
4.8k points

1 Answer

3 votes

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.");

}

}

}

Step-by-step 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

}

}

}

User Ian Vaughan
by
5.5k points