Situation: you need to get the type byte after the operation int/int . If the result is in the byte range, then output it, if not, then output an error message. And also handle Exception when dividing by 0 and Exception in principle. How to make such a piece of code work? Tried in line 3 through byte tempResult = (byte) (operand1 / operand2); but in the end received for the last call is not what you need.

 public byte divisionByte(int operand1, int operand2) { try { byte tempResult = operand1 / operand2; if (tempResult >= 127 && tempResult <= -128) { System.out.println("Результат не входит в диапазон Byte."); } else System.out.println(operand1 + " / " + operand2 + " = " + tempResult); return tempResult; } catch (ArithmeticException e) { System.out.println(operand1 + " / " + operand2 + " = We can't divide by 0. " + e + ". Shame on you!"); return 1; } catch (Exception e) { System.out.println("ERROR " + e); return 1; } } 

In the Main class, one call should give a value, the second error message when dividing by 0 , the third that "Результат не входит в диапазон Byte"

 calc.divisionByte(2, 2); calc.divisionByte(2, 0); calc.divisionByte(1000, 2); 

    1 answer 1

    You must divide into int , check the range, and only then convert to byte . If you immediately convert to byte , then, for example, the value 257 will silently turn into 1, and the result will be wrong. In your code, the condition tempResult >= 127 && tempResult <= -128 will never be broken, because the tempResult type tempResult already byte !

    Change the type tempResult to int .


    The correct design for such a function would be to report problems with different types of exceptions. Writing to the console in the division function is very bad. Perhaps the user of the function does not use it at all in the console application. Or an application console, but he brought something to the console before calling the function, and expects to output something after.