0
I’m doing an activity that consists of a simple calculator, but accepts operations with multiple operators (example: 1+2+3-4 = 2).
I have already made a Try catch to handle the error if the user type a letter in place of the numbers (natural error that the compiler itself would detect), but do not know how to make a Try catch for when the user type an operator that is not (+ - * /).
Follow the code. Thank you.
public class TestaCalculadora {
public static void main(String[] args) {
double p1=0, p2=0;
char op=' ';
boolean continua=true, continua2=true;
Scanner sc = new Scanner(System.in);
do {
try {
System.out.print("Número: ");
p1 = sc.nextDouble();
System.out.print("Operador: ");
op = sc.next().charAt(0);
continua=false;
}
catch (Exception e) {
System.err.println("Insira apenas números.");
sc.nextLine();
}
} while(continua);
do {
try {
do {
System.out.print("Número: ");
p2 = sc.nextDouble();
switch (op) {
case '+':
p1=Calculadora.somar(p1, p2);
break;
case '-':
p1=Calculadora.subtrair(p1, p2);
break;
case '*':
p1=Calculadora.multiplicar(p1, p2);
break;
case '/':
p1=Calculadora.dividir(p1, p2);
break;
}
System.out.print("Operador: ");
op = sc.next().charAt(0);
} while(op!='=');
System.out.printf("Resultado = %.2f ",p1);
continua2=false;
}
catch (Exception e) {
System.err.println("Insira apenas números.");
sc.nextLine();
}
} while(continua2);
}
}
Do not use
try-catch
including thiscatch (Exception)
should not be used because it captures possible errors that are not what you expect.– Maniero