Chapter 7 #9, p. 387; Programming Exercises; JAVA PROGRAMMING; 8th Edition; Joyc
ID: 3763630 • Letter: C
Question
Chapter 7 #9, p. 387; Programming Exercises; JAVA PROGRAMMING; 8th Edition; Joyce Farrell. THANK YOU!!!
use import javax.swing.JOptionPane THANK YOU!
#9. Write a program that inserts parentheses,a space, and a dash into a string of 10 user-entered numbers to format it as a phone number. For example, 5153458912 became (515) 345-8912. If the user does not enter exactly 10 digits, display an error message. Continue to accept user input until the user enters 999. Save the file as PhoneNumberFormat. java
Explanation / Answer
import java.util.Scanner;
public class PhoneNumberFormat {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print(" Enter the Phone Number :");
String textPhone = scanner.nextLine();
if (textPhone.contains("999"))
break;
if (textPhone.matches("[0-9]+") && textPhone.length() == 10) {
System.out.println("phoneNumber : " + "("
+ textPhone.substring(0, 3) + ") "
+ textPhone.substring(3, 6) + "-"
+ textPhone.substring(6, 10));
} else {
System.out.println("Error message !");
}
} while (true);
scanner.close();
}
}
OUTPUT:
Enter the Phone Number :5153458912
phoneNumber : (515) 345-8912
Enter the Phone Number :1235897
Error message !
Enter the Phone Number :999
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.