bhxbr922
bhxbr922

Reputation: 47

Exception with Long.MAX_VALUE

I need a method that reads numbers from the file ( 1 2 3 4 5) and finds its sum, if the sum is greater than Long.MAX_VALUE. it throw an exception. Question: how to check Long.MAX_VALUE and which class to use in the method itself?

The method itself:


  public static long findSum (String path) throws FileNotFoundException, AccessDeniedException, BadFormatException, MaxValueException, IOException {
         String result1 = readFirstLine (new File ("C: \\ input.txt"));
         String file1 = result1.replaceAll ("\\ s +", "");
         long x = Long.parseLong (file1);
         long i = 0;
         while (x! = 0) {
             i = i + x% 10;
             x = x / 10;
             if (i> Long.MAX_VALUE)
                 throw new MaxValueException ("The sum exceeds the permissible values of Long.MAX_VALUE");
         }
         return i;

Upvotes: 0

Views: 406

Answers (2)

user4910279
user4910279

Reputation:

If the file contents are "1 2 3 4 5", then x = 12345, i = 15 (1+2+3+4+5).

x >= i is always true.

If huge numbers are entered, Long.parseLong(file1) will throw NumberFormatException first.

So you don't need to check for i. You should worry about Long.parseLong(file1).

Upvotes: 0

Andreas
Andreas

Reputation: 159114

Use Math.addExact​(long x, long y) (added in Java 8):

Returns the sum of its arguments, throwing an exception if the result overflows a long.

Throws ArithmeticException if the result overflows a long

i = Math.addExact​(i, x % 10);

UPDATE

Since I believe the intent of that code is to reverse the long value, you forgot to multiply i by 10, which means that you also need to use multiplyExact​(long x, long y) , or multiplyExact​(long x, int y) (added in Java 9):

i = Math.addExact(Math.multiplyExact(i, 10), x % 10);

Upvotes: 4

Related Questions