I have a program called public class ZeroCounter {. I want to add a new method to it called numberOfDigits() and add a line to test it in the main() method. How should I go abo
Try this.... :)
public class ZeroCounter {
public static int numberOfDigits(int number)
{
//return Integer.toString(number).length();
return String.valueOf(number).length();
}
public static void main(String[] args)
{
int number;
Scanner Keyboard=new Scanner(System.in);
System.out.print("Enter the number: ");
number=Keyboard.nextInt();
System.out.println("numberOfDigits(" + number + ")=" + numberOfDigits(number));
}
}
Updated Code..
import java.util.*;
public class ZeroCounter
{
public static int numberOfDigits(int number,char d)
{
//to get a char array of digits of number
char[] n=Integer.toString(number).toCharArray();
int r=0;
for(char x:n)
{
if(x==d)
r++;
}
return r;
}
public static void main(String[] args)
{
int number;
char digit;
boolean flag=false;
Scanner Keyboard=new Scanner(System.in);
try{
System.out.print("Enter the non-negative number: ");
number=Keyboard.nextInt();
//to check number is positive or not
if(number<=-1)
throw new Exception();
System.out.println(number + " contains " + numberOfDigits(number,'0') + " zeros.");
System.out.print("Enter the digit: ");
//to take only one letter as input
digit=Keyboard.next(".").charAt(0);
//to check input is digit or not
if(!Character.isDigit(digit))
throw new Exception();
System.out.println("Number of digits(" + digit + ")=" + numberOfDigits(number,digit));
}
//to catch all exceptions
catch(Exception e)
{
System.out.println("\n You have entered invalid input..");
}
}
}