In: Computer Science
In.java
A phone number has the format (xxx)yyy-zzzz ( e.g.(942)731-2262
). Write a program that reads a string and formats it as a phone
number. First it should check that the string has exactly 10
symbols. If it does, the program will print the formatted version.
If the string does not have exactly 10 symbols, print Invalid and
do not process it.
You do NOT need to verify that the symbols in the string are
digits.
Sample run 1... This program will format a string as a phone number. Enter the number: 9427312262 Formatted number: (942)731-2262 Bye. Sample run 2... This program will format a string as a phone number. Enter the number: 43534565 Not a valid number. Please enter another one: 9427312262 Formatted number: (942)731-2262 Bye. Sample run 3 ... This program will format a string as a phone number. Enter the number: 345345 Not a valid number. Please enter another one: 1234556 You missed your second try! No more chances! Bye.
import java.util.Scanner; public class ProcessPhone { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("This program will format a string as a phone number."); System.out.print("Enter the number: "); String number = in.nextLine(); if (number.length() != 10) { System.out.print("Not a valid number. Please enter another one: "); number = in.nextLine(); if (number.length() != 10) { System.out.println("You missed your second try! No more chances!"); System.out.println("Bye."); return; } } System.out.printf("Formatted number: (%s)%s-%s\n", number.substring(0, 3), number.substring(3, 6), number.substring(6)); System.out.println("Bye."); } }