I'm trying to do a basic project for class, but I've run into an issue. When validating the code, it works when "test@test.com" is entered. However, when further testing and say inputting "test@test.com.com" is entered, it still returns valid. Here's the code:
System.out.println("Enter a valid email address: "); Scanner scan = new Scanner(System.in); emailAddress = scan.next(); 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); if (b) { System.out.println("The email address \"" + emailAddress + "\" is valid."); } else { System.out.println("The email address \"" + emailAddress + "\" IS NOT valid."); } } while (!b);
It functions like it's supposed to, minus knowing to mark "test@test.com.com" or any other similar email format as invalid. Suggestions would be appreciated!
EDIT: I'll add the instructions and the feedback I received.
The instructions: An email address contains the @ character. Write a program that takes asks for an email address input from the user and determines whether it is a valid address or not. This is based on the presence of the @ character and no spaces in the string. You do not need to worry about any other characters in the input word. Output the result "The word IS an email address" or "The word IS NOT an email address"
Example - Input: testuser@mydomain.com Output: The word IS an email address
Input: my123user Output: The word IS NOT an email address
My feedback:
Program incorrectly identifies test@test.com.com as a valid email. Code is not formatted properly and indentation is incorrect. Please ensure your code is indented properly with each new set of curly brackets (which indicates scope).