-2

Solved: The problem was that the integer's values were too high and thus could not be stored in a int, but rather had to be stored in a BigInteger.

This code is intended to read input from a file(shown below) and I would like it to be read as an int or parsed to an int as I need to be able to apply math to it. It always throws the exception, "InputMismatchException". I have read many other questions and their solutions and still to implement their solutions with little to no success. The solutions include parsing the string as an int, removing whitespace with "ReplaceAll".

Code:

String fileName = "SBOWorkSpace.txt";
Scanner sf = new Scanner(new File(fileName));

int lineint = sf.nextInt();
int finalnumbers = lineint * hour;
System.out.println(finalnumbers + hournum);

String linestring = sf.nextLine();
String nospaces = linestring.replaceAll("\\s+\\u00A0]+$", "");
int filetonumbers = Integer.parseInt(nospaces);

File:

46886794368454912286794394376459086711

Error:

Exception in thread "main" java.util.InputMismatchException: For input string: "46886794368454912286794394376459086711"
at java.util.Scanner.nextInt(Scanner.java:2097)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Encryption.main(Encryption.java:881)
Shadow
  • 9
  • 5

3 Answers3

3

The Java class Integer has a maximum value, 2^31 - 1, which is the 10-digit number 2147483647. The number you are trying to put in an Integer has 38 decimal digits, so it is much larger than the largest number an Integer can hold and Java will not let you put it in an Integer.

You might want to try working with BigInteger instead. For example,

BigInteger filetonumbers = new BigInteger(nospaces);

If you search SO for "biginteger" and "java", you will find a lot of questions and answers; some of these are irrelevant to you, but some others discuss java.math.BigInteger and show some examples of the class being used in non-trivial ways.

Community
  • 1
  • 1
David K
  • 3,147
  • 2
  • 13
  • 19
  • Thank you, could you possibly give me an example of how to use BigInteger, I read through the link you provided and am still unsure of how to use it. – Shadow May 12 '16 at 12:30
  • You won't be able to convert it to a primitive like with `parseInt`; you'd have to actually store all your numbers (at least any big ones) in `BigInteger` objects and learn the functions that allow you to do math operations with them (for example, you can't use `+` to add two BigIntegers, but you can use the `add` function). I added another starting link to the answer. – David K May 12 '16 at 16:58
0

The length of a int is from- 2,147,483,648 to 2,147,483,647 and you are assigning large value that is beyond int capacity it is also large from the capacity of long datatype

Sharad Gautam
  • 91
  • 5
  • 11
0
at java.util.Scanner.nextInt(Scanner.java:2097)

Maybe the scanner can't parse your int cause it's too large to be an int ?

Maximum value of an int32

Community
  • 1
  • 1
Alexis Delahaye
  • 644
  • 5
  • 18