0

I'm having trouble trying to find the length of a int inputted. I converted the int value into a string and it works perfectly up until the user inputs any int that has more than 10 digits. The program will print out how many digits were inputted but it gives some boundary error once I put anything >10 digits

  answer = in.nextInt();
  answerString = String.valueOf(answer);
  answerLength = answerString.length();
  System.out.println(answerLength);
ricemvm
  • 7
  • 2
  • String size is limited to 32 bits which means its range is between `-2147483648` and `2147483647` (inclusive). If you provide number which is out of max value you will get exception. To suggest any proper solution we would need to know what you really want to do in your code but consider using `hasNextInt` before you invoke `nextInt`. If result is `false` you can consume incorrect value with `next`. You can also use `nextBigInteger` – Pshemo Mar 23 '16 at 00:26

4 Answers4

0

take input as String even if it is integer value, see below code.

String answer = in.nextLine(); 

System.out.println(answer.length());
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Rahul Akula
  • 135
  • 1
  • 10
  • Cannot do that, because later I will need to be able to select individual digits and add them and that would be too inefficient – ricemvm Mar 23 '16 at 00:28
  • `nextLine` will read entire line, not single token. This could case problems if someone would provide few numbers in one line. – Pshemo Mar 23 '16 at 00:28
0

The reason for this is because the max value for an Integer is 2147483647. If you need more digits than that consider using long.

JanLeeYu
  • 981
  • 2
  • 9
  • 24
apicellaj
  • 233
  • 1
  • 3
  • 16
0

Using more than 10 digits goes over Integer.MAX_VALUE. BigInteger would be more suitable in your case, but be aware of its memory restrictions as mentioned here.

Community
  • 1
  • 1
David Fernandez
  • 585
  • 1
  • 6
  • 20
0

Just use Long answer = in.nextLong(); instead

Seda
  • 243
  • 1
  • 9
  • It is worth noting that this solution simply moves problem to values bigger than `9223372036854775807` (19 digits) where in case of `nextInt` max value is `2147483647` (10 digits). – Pshemo Mar 23 '16 at 00:35