1

I have to create a Calculator in Java, based on this Interface.

public interface CalculatorIF {
    int add(int x, int y);
    int sub(int x, int y);
    int mult(int x, int y);
    //double div(int x, int y);
    //int sqrt(int x);
}

But for every Method, I need pre-post conditions. I really need help for pre-conditions, because I can't imagine even a single one which makes sense and isn't already handled by Java.

EDIT: division and sqrt are clear to me, but I need some Ideas for add, sub and mult.

koin
  • 203
  • 2
  • 12
  • What do you mean handled by java? – ItamarG3 Nov 05 '16 at 18:48
  • I mean for my add-method I only can Imagine as a pre-condition x or y is greater than Integer.MAX_VALUE but this is already handled by java. – koin Nov 05 '16 at 18:49
  • precondition for sqrt is non-negative? or for div is `y!=0`? maybe I'm just mistaken but that might be it – ItamarG3 Nov 05 '16 at 18:50
  • Division by zero? Square root of negative numbers? Java will throw an ArithmeticException in case of division by zero and return NaN, in which case you should check in the sqrt method whether int x is negative, and it if it, throw an appropriate exception... – nvkrj Nov 05 '16 at 18:52
  • If there's nothing to check, there's nothing to check – baao Nov 05 '16 at 18:57
  • Yes, sorry I forgott to mention that I just need some for add, sub and mult. Division y!=0 and sqrt x >= 0 was quite easy. @baao yes, but It's written explicit in my task so I was kinda worried Im missing something – koin Nov 05 '16 at 18:57

1 Answers1

1

If you add two Integer.MAX_VALUE values, the result will not fit int and will be truncated. On the other hand, if the input domain is restricted, we can always guarantee that the result is not truncated and has an expected value instead.

For example, if x <= Integer.MAX_VALUE / 2 and y <= Integer.MAX_VALUE / 2, then the sum x + y will be less than or equal to Integer.MAX_VALUE, so there will be no truncation for positive integers. Similar reasoning can be used for negative values and Integer.MIN_VALUE. Preconditions for subtraction can be done the same way.

For multiplication, if either operand absolute value is less than sqrt (Integer.MAX_VALUE), their product will be inside the range of int.

More sophisticated ways to detect overflow and underflow are possible, but for a class exercise such preconditions seem to be fine.

Alexander Kogtenkov
  • 5,770
  • 1
  • 27
  • 35