Why can’t Java tell me when I can’t use integers?

For a small project (question 10 Euler), I try to sum up all primes less than 2 million So I use a powerful method to iterate from 0 to 2000'000 and check whether the number is prime If I add it to the sum:

private int sum = 0;

private void calculate() {
   for (int i = 0; i < 2000000; i++) {
      if (i.isPrime()) {
         sum = sum + i;
      }
   }
   sysout(sum)
}

This calculation result is 1179908154, but this is incorrect So I changed int to BigInteger, and now I get the correct sum 142913828922 Obviously, the scope of int is overflowed But why can't Java tell me? (e.g. exceptions)

Solution

As you can imagine, you might want it to be represented as a traditional integer Exceptions are reserved for absolute and unalterable errors

ETA: language specification:

( http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html )

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>