In: Computer Science
Write a java program to accept a telephone number with any number of letters. The output should display a hyphen after first 3 digits and subsequently a hyphen (-) after very four digits. Also, modify the program to process as many telephone numbers as the user wants
code optimization: no unnecessary variables , if statements and counters
sample output screen shown with 3 cases(atleast one with blank spaces ect.)Descriptive block and inline comments include.
For single phone no.:
import java.util.*;
public class Telephone {
public static void main(String[] args) {
String phoneNo; //To
read the telephone no.
//mark stores the mark
where a hyphen will be placed
//count is a counter
that counts the no. of characters passed
int i, mark = 3, count = 0;
Scanner sc = new
Scanner(System.in);
System.out.print("Enter a telephone number: ");
phoneNo = sc.nextLine();
System.out.print("Telephone no. with hyphens: ");
for(i = 0; i < phoneNo.length(); i++)
{
if(Character.isDigit(phoneNo.charAt(i))) //if character is a
digit
{
System.out.print(phoneNo.charAt(i)); //print no.
count++; //increase count by 1
if(count == mark && i != phoneNo.length() - 1){
//if count reaches mark and the digit is not the last
System.out.print("-");
count = 0; //reset count
if(mark == 3) //after first three digits, mark changes to 4
mark = 4;
}
}
}
System.out.println();
}
}
Output:
To modify the program for more than one telephone numbers, we just have to insert the same task in a loop. The code has been given below:
For more than one number:
import java.util.*;
public class Telephone {
public static void main(String[] args) {
String phoneNo; //To
read the telephone no.
//mark stores the mark
where a hyphen will be placed
//count is a counter
that counts the no. of characters passed
int i, mark, count, n;
Scanner sc = new
Scanner(System.in);
System.out.print("How many nos. you want to enter:
");
n =
Integer.parseInt(sc.nextLine());
while(n > 0){
//Iterating the same task for n times
System.out.print("Enter a telephone number: ");
phoneNo = sc.nextLine();
System.out.print("Telephone no. with hyphens: ");
count = 0;
mark = 3;
for(i = 0; i < phoneNo.length(); i++)
{
if(Character.isDigit(phoneNo.charAt(i))) //if character is a
digit
{
System.out.print(phoneNo.charAt(i)); //print no.
count++; //increase count by 1
if(count == mark && i != phoneNo.length() - 1){
//if count reaches mark and the digit is not the last
System.out.print("-");
count = 0; //reset count
if(mark == 3) //after first three digits, mark changes to 4
mark = 4;
}
}
}
System.out.println();
n--; //Decrementing n
}
}
}
Output: