Throwing Exceptions

Hi all,

I am try'n to throw an exception if the arguments for this codes produces a value out of the int range but it is not working need help

codes:

public static int mult(int x, int y) {

if (x == 0 || y == 0) {

return 0;

} else if((x * y)<= Integer.MAX_VALUE){

return (mult(x, (y - 1)) + x);

}

throw new IllegalArgumentException("Value " + x + " Or " + y

+ " is not a natural number or cannot"

+ " produce a value in the int range");

[513 byte] By [meetbishopa] at [2007-11-26 18:13:28]
# 1
You could do something along the lines ofif (x <= Integer.MAX_VALUE/y)I think you need to think of the positive as well as negative cases. And perhaps truncation in the division needs to be considered, too.
DrLaszloJamfa at 2007-7-9 5:46:33 > top of Java-index,Java Essentials,New To Java...
# 2

int1 <op> int2

will always yield an int result. For instance, Integer.MAX_VALUE * Integer.MAX_VALUE is 1. Any int value will always be <= Integer.MAX_VALUE.

You could cast one or both values to long before doing the mult, but as mentioned, you'd have to make sure the result is both >= Integer.MIN_VALUE and <= Integer.MAX_VALUE.

jverda at 2007-7-9 5:46:33 > top of Java-index,Java Essentials,New To Java...
# 3
Thanks very much its working now.
meetbishopa at 2007-7-9 5:46:33 > top of Java-index,Java Essentials,New To Java...