Need help solving code Objectives Use Scanner class to get user input and System
ID: 3839371 • Letter: N
Question
Need help solving code
Objectives Use Scanner class to get user input and System.out.println() to display output. Use String class methods to extract and replace digits in a string. Background Reading Horstmann, Java For Everyone, Chapter 3. ZyBook, Section 3. Assignment Lab3d Write a Java program that asks the user to enter a 10-digit string as a typical U.S. telephone number, extracts the 3-digit area code, the 3-digit 'exchange, " and the remaining 4-digit number as separate strings, prints them, and then prints the complete telephone number in the usual formatting with parentheses. If the user does not enter a 10-digit number, print an error message. Requirements: The name of the Java class is Lab3d. Your "identification string" should be the first comment of the main method.//Program 3, [Name] f [csscId] For example, in my program this would be://Program 3, Patty Kraft, cssc0460 The prompt should be on its own line with the following text (i.e. use System.out.printin()): Enter 10-digit telephone number: Print the number entered. Print the area code Print the exchange Print the last four numbers Print the formatted number A sample run would look like: Enter 10-digit telephone number: 1234567890 You entered 1234567890 The area code is 123 The exchange is 456 The number is 7890 The complete telephone number is (123) 456-7890 A sample run with an invalid number would look like: Enter 10-digit telephone number: 123456789 You entered 123456789 Please enter a 10-digit numberExplanation / Answer
Lab3d.java
import java.util.Scanner;
public class Lab3d {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String phoneNum = "";
System.out.println("Enter 10-digit telephone number: ");
phoneNum = scan.next();
if(phoneNum.length() != 10){
System.out.println("Please enter a 10-digit number.");
}
else{
System.out.println("You entered: "+phoneNum);
String areaCode = phoneNum.substring(0,3);
String exchangeCode = phoneNum.substring(3,6);
String number = phoneNum.substring(6,10);
System.out.println("The area code is "+areaCode);
System.out.println("The exchange is "+exchangeCode);
System.out.println("The number is "+number);
System.out.println("The complete telephone number is ("+areaCode+") "+exchangeCode+"-"+number);
}
}
}
Output:
Enter 10-digit telephone number:
1234567890
You entered: 1234567890
The area code is 123
The exchange is 456
The number is 7890
The complete telephone number is (123) 456-7890
Enter 10-digit telephone number:
123456789
Please enter a 10-digit number.