Exercise
Digits in a number
Objetive
Write a java program to calculate the number of digits in a positive integer (hint: this can be done by repeatedly dividing by 10). If the user enters a negative integer, the program should display a warning message and proceed to calculate the number of digits for the equivalent positive integer.
For example:
Number = 32
2 digits
Number = -4000
(Warning: it is a negative number) 4 digits
Example Code
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int number;
int digit = 0;
System.out.print("Number? ");
number = Integer.parseInt(new Scanner(System.in).nextLine());
if (number < 0)
{
System.out.println("(Warning: it is a negative number)");
number = -number;
}
while (number > 0)
{
number = number / 10;
digit++;
}
if (digit == 0)
{
digit = 1;
}
System.out.printf( digit + " digits" + "\r\n");
}
}