202k views
0 votes
Write a method, isEmailAddress, that is passed a String argument. It returns true or false depending on whether the argument has the form of an email address. In this exercise, assume that an email address has one and only one "@" sign and no spaces, tabs or newline characters.

1 Answer

5 votes

Answer:

//Method declaration taking a parameter called myString of type String

public static boolean isEmailAddress (String myString){

//checking the @ character exists in string

if (myString.indexOf("@") != -1) {

//checking if only one instance of @ exist in the string

if (myString.indexOf("@") == myString.lastIndexOf("@")) {

//checking if there's no space character

if (myString.indexOf(" ") == -1) {

//checking if there's no newline character in the string

if (myString.indexOf("\\") == -1) {

// checking if there's no tab character in the string

if (myString.indexOf("\t") == -1) {

return true;

}

}

}

}

}

return false;

}

Step-by-step explanation:

The method takes in a string which is supposed to be an email address and checks if it is a valid email, it returns true if it is a valid email and returns false if not. the method checks the following conditions along the way.

->If "@" exists

->If there's only one "@" in the string

->If space character does not exists

->If newline character does not exists

->If tab character does not exist

it returns true if all the conditions are true.

User Prabhu
by
5.2k points