Modify Java program to accept a telephone number with any nu
Modify Java program to accept a telephone number with any number of the letters, using the if else loop. The output should display a hyphen after the first 3 digits and subsequently a hyphen (-) after every four digits. Also, modify the program to process as many telephone numbers as the user wants.
Solution
Please follow the code and comments for description :
CODE :
import java.util.HashMap; // required imports for the code to run
import java.util.Map;
 import java.util.Scanner;
public class Telephone { // calss to run the methods
public static void main(String[] args) { // driver method
   
 Scanner sc = new Scanner(System.in); // scanner class to get the data from the user
System.out.print(\"Enter the Telephone letters : \"); // prompt the user to enter the data
 String input = sc.nextLine(); // get the data
 String lowerInput = input.toLowerCase(); // converting the data to lowercase
TeleNumProcessor NumProcessor = new TeleNumProcessor(lowerInput); // creating an object ofr the class and pass the data
 String result = NumProcessor.process(); // call the method and save the result
 System.out.println(\"---------------------------------------------------\"); // print the data to console
 System.out.println(\"The Entered Telephone letters are : \" + input);
 System.out.println(\"The Phone number is : \" + result);
 System.out.println(\"---------------------------------------------------\");
  }
}
class TeleNumProcessor { // class that gets the numbers for the input
Map<String, String> match = new HashMap<>(); // map that stores the matching numbers
 String strToProcess; // required initialisations
public TeleNumProcessor(String strToProcess) { // method that takes the input and returns the number string
 this.strToProcess = strToProcess;
 match.put(\"[a-c]\", \"2\"); // saving the data to the map for the patterns
 match.put(\"[d-f]\", \"3\");
 match.put(\"[g-i]\", \"4\");
 match.put(\"[j-l]\", \"5\");
 match.put(\"[m-o]\", \"6\");
 match.put(\"[p-s]\", \"7\");
 match.put(\"[t-v]\", \"8\");
 match.put(\"[w-z]\", \"9\");
 }
public String process() { // method to process the input data
if (!\"2\".equals(strToProcess)) { // checking if the input is 2 or not
 match.forEach((regex, replacement) -> { // method to check for the regex pattern matcher
 strToProcess = strToProcess.replaceAll(regex, replacement); // replace the dat and place it to the string
 });
 }
 return strToProcess.substring(0, 3) + \"-\" + strToProcess.substring(3, 7); // return the formatted data
 }
 }
OUTPUT :
Enter the Telephone letters : fewfwef
 ---------------------------------------------------
 The Entered Telephone letters are : fewfwef
 The Phone number is : 339-3933
 ---------------------------------------------------
 Hope this is helpful.


