简体   繁体   中英

How to display the number of digits in a positive number

I have the code here but I'm not sure how to display the number of digits once I get the user input as an int .

public class Chapter8 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n;
        System.out.print("Enter a positive integer: ");
        n = in.nextInt();
        if (n <= 0) {
            while (n != 0) {
                System.out.println(String.format("%02d", 5));
        } 
    }
} 

You can count by dividing the number by 10. each time the number will be shortened by 1 digit until the number reach 0 :

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n;
    System.out.print("Enter a positive integer: ");
    n = in.nextInt();
    int counter = 0;
    while(n > 0){
        n = n / 10;
        counter++;
    }
    System.out.println(counter);
}

One quick solution is to convert the integer into a string and then measure how many characters it has:

String myNum = String.valueOf(n);
System.out.println(myNum.length());

You could simply go ahead by converting the integer into a char array.

int x = 20;
char[] chars = x.toCharArray();

Then you can get the length of the array.

int numberOfDigits = chars.length();

Hope it helps.

In case your teacher is tricky like I would be, this gives you the number of digits entered as well as the number of digits in the resulting int...

import java.util.Scanner;

public class StackOverflow_32898761 {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        try
        {
            int n;

            System.out.println("Enter a positive integer: ");
            String value = input.next();

            try
            {
                n = Integer.parseInt(value);

                if (n < 0)
                {
                    System.out.println("I said a POSITIVE integer... [" + value + "]");
                }
                else
                {
                    System.out.println("You entered " + value.length() + " digits");
                    System.out.println("The resulting integer value has " + String.valueOf(n).length() + " digits");
                    System.out.println("The integer value is " + n);
                }           
            }
            catch (Exception e)
            {
                System.out.println("Invalid integer value [" + value + "]");
            }
        }
        finally
        {
            input.close();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM