Solve mathematical expressions in java using string

Asked

Viewed 452 times

1

I cannot make this code solve the expressions contained in the database. In the database, the expressions are like this:

All expressions registered in the database follow the pattern described below:

$expressao = "$x$op1$y$op2$z$op3$w$op4$k";

Where:

$operadores = array('+', '*', '/', '-');
$op1 = $operadores[rand(0,3)];
$op2 = $operadores[rand(0,3)];
$op3 = $operadores[rand(0,3)];
$op4 = $operadores[rand(0,3)];
$x = rand(1111111111,9999999999).rand(1111111111,9999999999).rand(1111111111,9999999999);
$y = rand(1111111111,9999999999).rand(1111111111,9999999999).rand(1111111111,9999999999);
$z = rand(1111111111,9999999999).rand(1111111111,9999999999).rand(1111111111,9999999999);
$w = rand(1111111111,9999999999).rand(1111111111,9999999999).rand(1111111111,9999999999);
$k = rand(1111111111,9999999999).rand(1111111111,9999999999).rand(1111111111,9999999999);

Example:

136745704413540771491283768999*132288955513943880221144001435+131540870513
718749541202397273/136652154113069665481264184389/126364152611910743531217
601923


public class SD {
    static double res;
    static int id ;

    public SD() {
    }
    public static Connection con = null;

    public static void Conectar() {
        System.out.println("Conectando ao banco...");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/basedados", "root", "pass");
            System.out.println("Conectado.");
        } catch (ClassNotFoundException ex) {
            System.out.println("Classe não encontrada, adicione o driver nas bibliotecas.");
           Logger.getLogger(SD.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException erro) {
            System.out.println("Erro: " + erro);
            throw new RuntimeException(erro);
        }
    }

    public String Retirar() {
        Conectar();

        String nome = "Fillipe";
        String expressao = null;
        List<String> x = new ArrayList<>();
        try {
            PreparedStatement ps = con.prepareStatement("{call retira_exp(?)}");
            ps.setString(1, nome);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
               x.add(rs.getString(2));
               id = Integer.parseInt(rs.getString(1));

            }
           // for (String exp : x) {
           // }
        } catch (SQLException e) {
            System.out.println("Erro: " + e);
        }
        expressao = x.get(0);


        return expressao;

    }


       public static double Calcular() {
        SD obj = new SD();
        String expr = obj.Retirar();
        System.out.println("Expressao: " + expr);

       // double a = Double.parseDouble(expr);

        String [] valores = expr.split("\\+|\\-|\\*/|\\-");
        String [] op = expr.split("\\d+");
        // op[1] = primeiro operador
        if(op[1].equals("+")){
            //resultado = valor[i] + valor[i+1]
        }


        return res;
    }

    public void EntregaResultado() {

        Double result = Calcular();
        System.out.println("Resultado: " + result);
        try {
            PreparedStatement pstm = con.prepareStatement("{call entrega_res(?,?)}");
            pstm.setInt(1, id);
            pstm.setDouble(2, result);
            pstm.executeUpdate();

        } catch (SQLException e) {
            System.out.println("Erro: " + e);
        }
    }

    public static void main(String[] args) {
       // SD.Conectar();
        SD sd = new SD();
        sd.EntregaResultado();

    }

}
  • 1

    What problem exactly are you having?

  • so, I’m not able to implement the method that calculates the expression that is contained in the bank, this code takes the expression , solves and returns the answer , the other parts I was able to do only the one of the calculation that I do not know how it starts

  • the code is removing the expression and returning to the bank, only without the result of the expression

1 answer

1


I would make a method to calculate recursively. Note that you have to prioritize division and multiplication.

public static double CalcularRecursivo(String []valores, String[] operadores) {   
    // o array de valores sempre vai ter um elemento a mais do que o de operadores
    // e o operador i é sempre referente a operacao entre os valores[i] e valores[i + 1]

    // para cada operador em operadores
    //  se o operador[i] for / ou * (eles tem prioridade)
    //      faça a conta usando o valor[i] e valor[i + 1] e guarde o valor
    //          monte uma nova lista de valores e operadores, com o valor novo que calculou e sem o operador que já foi utilizado
    //          retorne CalcularRecursivo(novosValores, novosOperadores)

    // se chegou até aqui é porque não tem mais * e / na expressão
    // para cada operador em operadores
    //  se o operador for + ou - faça a mesma coisa de cima

}
  • aahh, ok Michelle thank you very much , I will try here

  • One tip is to create another class with public Static main and test only that method there, separate from that whole database code. There you create simple strings to test, like 8+5*0 and test to see if it works, if it won’t reset the expression. Invent some test cases like this. It will be much easier than fighting with those huge numbers that come from the database.

  • 1

    I managed to do... thank you very much for your help

  • 1

    Congratulations, @Hudsonrodrigues, you knew you could do it! Would you please put your solution in the text of your question? So someone else in the future who has the same doubt will be able to use it.

Browser other questions tagged

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