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 method to count digits of an integer number:-
public int numberOfZeros(int number){
return ((int) Math.log10(number) + 1);
}
Or you can try this code
//Declare input as scanner
Scanner input = new Scanner(System.in);
//Take input
System.out.println("Enter Number :");
no = input.nextInt();
System.out.println("Enter digit :");
digit = input.nextInt();
//add while loop
while(no>0)
{
m=no%10;
if(m==digit)
oc++;
no=no/10;
}
System.out.println("Digit occurred "+oc+" times");
public class ZeroCounter {
public static void main(String[] args) {
System.out.println("Enter a nonnegative number:");
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt( ) ;
System.out.println(number + " contains " + numberOfZeros(number) + " zeros.");
} // End of main
private static int numberOfZeros(int number) {
int result = ///// calculation
return result;
}
}
You might want to read up a bit more on Java and how classes, methods and functions work first before going any further however.
It should be:
public class ZeroCounter {
public static int numberOfDigits(int number) {
//- Implementation goes here.
}
public static void main(String[] args) {
int number;
//- Initialize number variable.
System.out.println("numberOfDigits(" + number + ")=" + numberOfDigits(number));
}
}
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..");
}
}
}