Find Number of Digits in Given Number in Java

Google Advertisements

Prev Tutorial Next Tutorial

Find Number of digits in Given Number Program in Java

Any number is a combination of digits, like 342 have three digits. For calculating the number of digits of any number user have three possibilities to input values.

  • Enter +ve Number
  • Enter -ve Number
  • Enter zero

Find Number of digits in Given Number in Java

import java.util.Scanner;
class Numofdigit 
{
public static void main(String[] args) 
{
 int no,a=0;
 Scanner s=new Scanner(System.in);
System.out.println("Enter any number : ");
 no = s.nextInt();

if(no<0)
{
no=no * -1;
}
else if(no==0)
{
no=1;
}
while(no>0)
{
no=no/10;
a++;
}
System.out.println("Number of Digits in given number is: "+a);
}
}

Output

Enter any number:
345
Number of Digits in given number is: 3

Syntax to compile and run java program

Syntax

for compile -> c:/javac Numofdigit.java
for run -> c:/java Numofdigit

Explnation of Code

  • Scanner s=new Scanner(System.in): are used for receive input from keyboard.
  • nextInt(): method are used for get integer type value from keyboard.
  • System.out.println("....."): are used for display message on screen or console.

Explanation of program

a=no%10;

Here we find remainder of given number, using Modulo Operator we find remainder of any number, Using this step we get only last digits.

a=no/10;

Here After dividing any number by 10 we get all digits except last digits.

Sum=Sum+a;;

Using this statement we find sum of all digits. In first iteration it add 0 and last digits and store in Sum variable, in second iteration it add Previous sum values and last digits of new number and again store in Sum variable, and so on upto while condition is not false.


Prev Tutorial Next Tutorial

Google Advertisements

We have more than 5 Groups which have 500000+ Members and some Pages have more than 100000+ members. If you want to post your article on our website/FB Group/FB Page please contact on hitesh.xc@gmail.com or 8076671483

Buy This Ad Space @$50 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 8076671483

Path variable is set for providing path for all Java tools like java, javac, javap, javah, jar, appletviewer which are used in java programming. All these tools are available in bin folders so we set path upto bin folders.

Classpath variable is set for providing a path for predefined Java classes which is used in our application. All classes are available in lib/rt.jar so we set classpath upto lib/rt.jar.

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user.

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects.

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: hitesh.xc@gmail.com or 8076671483