¿ How to check the number of characters of an int variable?

mauricio :

I want the user to type a phone number on my keyboard, and if the number has more than 9 characters, print it out.

System.out.println("your number :");
    int number = in.nextInt();

    if(number > 9) {
        System.out.println("the number has 10 or more characters");
    }

I do it like this but it doesn't work

Arvind Kumar Avinash :

Do it as follows:

System.out.println("your number :");
String number = in.nextLine();

if(number.length() > 9) {
    System.out.println("the number has 10 or more characters");
}

Notes:

  1. Scanner::nextLine returns a String whose length can be calculated using String::length.
  2. Most likely, you are not going to use this number for any mathematical calculation e.g. addition, subtraction etc. and therefore String type is most appropriate for it. Just in case, you need to convert it into an int or long value, you can use Integer.parseInt(number) or Long.parseLong(number) respectively.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374739&siteId=1