Respuesta :
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 while loop, 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
The program is an illustration of loops and conditional statements.
Loops are used to perform repeated operations, while conditional statements are used to make decisions
The program in Java, where comments are used to explain each line is as follows:
import java.util.*;
public class Main{
public static void main(String[] args) {
//This creates a Scanner object
Scanner input = new Scanner(System.in);
//This is repeated until the user enters 999
while(true) {
//This prompts the user for input
System.out.print("Phone number: ");
//This gets the input from the user
String phnNum = input.nextLine();
//If the phone number is 999, the loop is exited
if(phnNum.equals("999")){
break;
}
//If the length of the phone number is 10
if(phnNum.length() == 10){
//This creates the formatted output
phnNum = phnNum.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");
//This prints the formatted output
System.out.printf("Formatted output: %s \n", phnNum);
}
//If otherwise
else{
//This prints an error message
System.out.println("Input must contain exactly 10 numbers");
}
}
}
}
Read more about loops and conditional statements at:
https://brainly.com/question/14284157