settingsAccountsettings
Menusettings

Q: Fix Emails - Java Task (Maps)

+13 votes

You are given a sequence of strings, each on a new line, unitll you receive “stop” command. First string is a name of a person. On the second line you receive his email. Your task is to collect their names and emails, and remove emails whose domain ends with "us" or "uk" (case insensitive).

Print: {name} – > {email}

EXAMPLES:

Input

Output

Ivan

ivanivan@abv.bg

Petar Ivanov

petartudjarov@abv.bg

Mike Tyson

myke@gmail.us

stop

Ivan -> ivanivan@abv.bg

Petar Ivanov -> petartudjarov@abv.bg

 

asked in Java category by user matthew44

1 Answer

+1 vote
 
Best answer

You will need regex: https://regex101.com/ in order to solve this task;

I've used this regex to divide the email into 3 groups:

(.+)@(.+)\\.(.+)
  • group(1): before the @;
  • group(2): after the @ and before the dot (.);
  • group(3): after the dot (.) (this is the group we are looking for)

Here's my code:

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pr_07_FixEmails {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String name;
        String email;

        LinkedHashMap<String, String> map = new LinkedHashMap<>();//THE map WHERE WE WILL PUT THE name AND THE email AS STRINGS

        Pattern pattern = Pattern.compile("(.+)@(.+)\\.(.+)");//USING REGEX TO DIVIDE THE email INTO 3 GROUPS - group(1): BEFORE THE @; group(2): AFTER THE @ AND BEFORE THE DOT (.); AND group(3): AFTER THE DOT (.)

        while (!(name = sc.nextLine()).equals("stop")) {//GETTING THE name FROM THE CONSOLE
            email = sc.nextLine();//GETTING THE email FROM THE CONSOLE
            Matcher matcher = pattern.matcher(email);
            if (matcher.find() && matcher.group(3).equals("bg")) {//CHECKING WHETHER WE HAVE A MATCH AND (&&) THE matcher.group(3) IS bg
                map.put(name, email);//PUTTING THE name AND THE email INTO THE map
            }
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
        }
    }
}
answered by user mitko
edited by user golearnweb
...