Hi all!
I've been working on a problem from my Intro to Java class for a couple of weeks and I feel like I'm close. I turned it in and only got partial credit. Here goes: This program allows a user to enter a phone number, country code, area code, and local number. The program needs to print out, separately what each of those string variables will be. The catch is that in some countries, the length of each string can vary. Here is what I have so far and at this point i have smoke coming out of my ears and am about to give up:
import java.util.Scanner;
public class PhoneNumberDissector
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initialize the variables
String phoneNumber;
String countryCode;
String areaCode;
// 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();
// Test to see if character in location zero is not equal to "q"
if (phoneNumber.charAt(0) != 'q')
{
// Determine the String variable for countryCode
countryCode = (phoneNumber.substring(0,phoneNumber.indexOf('-')));
int sep = phoneNumber.lastIndexOf("-");
char dash = phoneNumber.charAt(1);
System.out.println("Country Code = " + countryCode);
if (dash == '-')
{
// Determine the String variable for areaCode
areaCode = phoneNumber.substring(2,5);
System.out.println("Area Code = " + areaCode);
}
else
{
areaCode = phoneNumber.substring(3,6);
System.out.println("Area Code = " + areaCode);
}
// Whatever is left over after the 2nd hyphen is now the local number
System.out.println("Local Number = " + phoneNumber.substring(sep+1));
}
else
{
phoneNumber = "q";
}
}while (phoneNumber != "q");
}
}
Thanks for any help you can give!
Thayland