What happens in your code is that you first calculate the value of all variables and only then inform the result, this way as soon as the flow of the algorithm reaches the line div = a / b
and if b is 0 it already shoots the ArithmeticException
and does not inform the other calculations, to solve just modify the order in which are made the calculations and impressions, you can for example inform the result as soon as calculate each variable, the solution would be like this:
public static void main(String[] args) {
int a, b, soma, resto, sub, div, mult;
String entrada;
try {
entrada = JOptionPane.showInputDialog("Informe um número inteiro");
a = Integer.parseInt(entrada);
entrada = JOptionPane.showInputDialog("Informe outro número inteiro");
b = Integer.parseInt(entrada);
soma = a + b;
JOptionPane.showMessageDialog(null, " A soma = " + soma);
sub = a - b;
JOptionPane.showMessageDialog(null, " A Subtração = " + sub);
mult = a * b;
JOptionPane.showMessageDialog(null, " A Multiplicação = " + mult);
div = a / b;
resto = a % b;
JOptionPane.showMessageDialog(null, " A divisão = " + div +
"\n O Resto da Divisão = " + resto);
} catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Não Pode Dividir!");
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Digite números inteiros!");
} catch (IndexOutOfBoundsException e) {
JOptionPane.showMessageDialog(null, "Fora dos limites permitidos!");
}
}
In this case it prints each calculation as soon as it is done and finally tries to do the division, if b
for 0 and to launch the ArithmeticException
only the value of the division will not be informed. Another solution would be to treat the ArithmeticException
only in the division calculation since it is only this block that fires that Exception (this would be the most recommended) you could do so:
public static void main(String[] args) {
int a, b, soma, resto, sub, div, mult;
String entrada;
try {
entrada = JOptionPane.showInputDialog("Informe um número inteiro");
a = Integer.parseInt(entrada);
entrada = JOptionPane.showInputDialog("Informe outro número inteiro");
b = Integer.parseInt(entrada);
soma = a + b;
JOptionPane.showMessageDialog(null, " A soma = " + soma);
sub = a - b;
JOptionPane.showMessageDialog(null, " A Subtração = " + sub);
mult = a * b;
JOptionPane.showMessageDialog(null, " A Multiplicação = " + mult);
try {
div = a / b;
resto = a % b;
JOptionPane.showMessageDialog(null, " A divisão = " + div +
"\n O Resto da Divisão = " + resto);
} catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Não Pode Dividir!");
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Digite números inteiros!");
} catch (IndexOutOfBoundsException e) {
JOptionPane.showMessageDialog(null, "Fora dos limites permitidos!");
}
}
That was my doubt, and it was resolved perfectly! Thank you very much.
– Diego Davi