Answer:
import java.util.Scanner;
public class PhoneNumber
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
System.out.print("Enter the phone number :");
String phoneNumber = input.nextLine();
if(phoneNumber.contains("999"))
break;
if(phoneNumber.length() == 10){
phoneNumber = phoneNumber.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");
System.out.printf("The formatted phone number is: %s \n", phoneNumber);
}
else
System.out.println("The phone number must be exactly 10 digits!");
}
}
}
Explanation:
- Unless we specify a breaking condition inside the <u>while loop</u>, it will iterate
- Ask the user for the phone number to be formatted
- Check if the phone number is 999, if yes, stop the loop
- If the phone number contains exactly 10 digits, format the phone number as requested using regex
- Print the formatted phone number
- If it has not 10 digits, print an error message