Specification: Write a class TelephoneNumber that will hold a telephone number.
ID: 3683013 • Letter: S
Question
Specification:
Write a class TelephoneNumber that will hold a telephone number. An object of this class will have the following attributes:
----areaCode - a three-digit integer
----exchangeCode - a three-digit integer
----number - a four-digit integer
This class will also have the following methods:
----TelephoneNumber(<String>) - A constructor that takes a String of the form xxx-xxx-xxxx OR xxx-xxxx if the area code is missing. Throw an exception if the input format is not valid.
Hint: To simplify the constructor, you can replace each hyphen in the telephone number with a blank.
----toString - returns a string in either of the two formats shown previously for the constructor.
Using a text editor (e.g. notepad), create a text file of several telephone numbers, using the two formats described previously. Write a program TelephoneReader that reads this file, displays the data on the screen.
Explanation / Answer
import java.util.Scanner;
2.
3.public class PhoneNumberDissector
4.{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
8.
// Initialize the variables
String phoneNumber;
String countryCode;
String areaCode;
13.
14.// Begin the main Do - While loop to check for "q" to end the program
do
{
// Get user phone number input or have user quit the program
System.out.println("Please enter a phone number in the form cc-area-local,");
System.out.println("where cc = country code digits, area = area code digits,");
System.out.println("and local = local phone digits.");
System.out.print("Or enter <q> to quit: ");
phoneNumber = stdIn.nextLine();
23.
// Test to see if character in location zero is not equal to "q"
if (phoneNumber.charAt(0) != 'q')
{
27.
// Determine the String variable for countryCode
countryCode = (phoneNumber.substring(0,phoneNumber.indexOf('-')));
int sep = phoneNumber.lastIndexOf("-");
31.
char dash = phoneNumber.charAt(1);
33.
System.out.println("Country Code = " + countryCode);
35.
if (dash == '-')
{
38.
// Determine the String variable for areaCode
areaCode = phoneNumber.substring(2,5);
System.out.println("Area Code = " + areaCode);
}
43.
else
{
areaCode = phoneNumber.substring(3,6);
System.out.println("Area Code = " + areaCode);
}
49.
50.
// Whatever is left over after the 2nd hyphen is now the local number
System.out.println("Local Number = " + phoneNumber.substring(sep+1));
}
54.
else
{
phoneNumber = "q";
}
59.
}while (phoneNumber != "q");
61.
62.
}
64.}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.