Digits in a number Learn programming Java

Lesson:

Flow Control


Exercise:

Digits in a number 33


Objetive:

Create a java program to calculate how many digits has a positive integer (hint: it can be done by dividing by 10 several times). If the user enters a negative integer, the program must show a warning message, and proceed with the equivalent positive number.

For example:
Number = 32
2 digits
Number = -4000
(Warning: it is a negative number) 4 digits


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");
	}
}