• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multiplication of large int numbers - how to throw an exception exactly when the result is corrupted  RSS feed

 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let us consider this class.



With the code such as the above, if I have to determine that the result of multiplication may be corrupted and then possibly throw an exception, is it possible?

Also when I parse an integer input from new Scanner(System.in) using nextLine(), trim() and then parseInt(), I get a NumberFormatException in two cases.
1. when the input cannot be converted into an integer - like say it is a String.
2. When the number is too large to be held by the int.

Is there a way I could have my catch block know which of the two cases has happened?

Thanks for your help.
Chan.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the value first as a BigInteger, it will support large values if no syntax problem arises.
Then you can check the size whether it fits into a plain integer.


 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow. Thanks. It's working.

Did you mean I create two try catch blocks. First with the BigInteger to hold the user input. If this test passes, I do my int assignment and then if I still get a NumberFormatException, I know it's because int limit is crossed?

Like this?



Chan.

 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chan Ag wrote:
Like this?


Yes.

However whether the string consists only of decimal digit characters can be checked with a simple regexp as well.
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that, Ivan.

I will find out more based on that information.

Thank you.
Chan.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!