How to make a Try catch with mathematical operators?

Asked

Viewed 117 times

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 this catch (Exception) should not be used because it captures possible errors that are not what you expect.

1 answer

0

In this case, specifically, I used the repeat control while.

Try this code:

package testacalculadora;

import java.util.Scanner;

class Calculadora {

    public static double somar(double x, double y) {
        return x + y;
    }

    public static double subtrair(double x, double y) {
        return x - y;
    }

    public static double multiplicar(double x, double y) {
        return x * y;
    }

    public static double dividir(double x, double y) {
        return x / y;
    }
}

public class TestaCalculadora {

    public static void main(String[] args) {
        double p1 = 0, p2 = 0;

        String op = ""; //Alterei aqui

        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(); //Alterei aqui
                //Alterei aqui
                while (!(op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/"))) {
                    System.out.print("Operador: ");
                    op = sc.next();
                }

                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(); 

                    //não permitir Divisão por zero:
                    if (op.equals("/")) {
                        while (Double.isInfinite(p1 / p2)) {
                            System.out.print("Segundo Número: ");

                            p2 = sc.nextDouble();
                        }
                    }
                    System.out.println(p2);
                    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(); //Alterei aqui
                    //Alterei aqui
                    while (!(op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/") || op.equals("="))) {
                        System.out.print("Operador: ");
                        op = sc.next();
                    }
                } while (!op.equals("=")); //Alterei aqui também

                System.out.printf("Resultado = %.2f  ", p1);
                continua2 = false;
            } catch (Exception e) {
                System.err.println("Insira apenas números.");
                sc.nextLine();
            }
        } while (continua2);

    }
}

  • I thought the best option would be to make a Try catch, thanks.

  • And for me to handle in case the user tries to divide by 0?

  • I changed the code. Check it out, please.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.