Reputation: 13
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int num = s.nextInt();
int a = num.length; //This part
System.out.println(a);
}
If I enter 4321, I want to get length of entered length. I already try to input Integer variable "a" but it did't right. T.T
(Example: length : 4) when I use int a = num.length;
, it did't get num's length as well as Strings When I want get "Hello".length();
It seem like did't exist. I want to get length but I don't know how.
Is there other way to get .length
?
Upvotes: 1
Views: 109
Reputation: 5083
Try with this
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int num = s.nextInt();
int length = String.valueOf(num).length();
System.out.println(length);}
if you want to get lenth of string then use bellow code
Scanner s = new Scanner(System.in);
String a = number.nextLine();
System.out.println(a.length());
Upvotes: 1
Reputation: 522
I would recommend to do it this way;
int length = String.valueOf(num).length();
or
int length = Integer.toString(num).length();
The obove mentioned solution with the + Operator works aswell but is considered to be rather dirty;
Upvotes: 1
Reputation: 59960
If you cast your int
to String
you then you can get its length for example :
int a = num.length;
String s = a + "";
int lng = s.length();
Upvotes: 1
Reputation: 393781
If you read the input as a String, you can obtain its length :
String num = s.next();
int a = num.length();
Upvotes: 0