Question: for this question Write a program that counts the number of times a digit appears in a telephone number. Your program should create an array
for this question
Write a program that counts the number of times a digit appears in a telephone number. Your program should create an array of size 10 that will hold the count for each digit from 0 to 9. Read a telephone number from the keyboard as a string. Examine each character in the phone number and increment the appropriate count in the array. Display the contents of the array.
I did this code.
import java.util.Scanner;
public class M7 {
public static void main(String[] args) {
String phonenumber;
int digits [ ] = new int [10];
Scanner key = new Scanner (System.in);
System.out.println("Enter a telephone number");
phonenumber = key.next();
for( int i=0; i < phonenumber.length(); i++)
{ String ch= phonenumber.substring(i,i+1);
int a= Integer.parseInt(ch);
digits[a]++;
}
for( int i=0; i < digits.length; i++)
System.out.println( digits[i]);
}
}
When I entered the phone number like this (312) 244-4677
it did not work and gave this message
Exception in thread "main" java.lang.NumberFormatException: For input string: "("
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at M7.main( M7.java:13)
How can I fix it?
Can anyone help me please to be the success?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
