-2

A single string contains two numbers and operator, the two numbers have to be detected and then do the mathematical operation.

I already did the part that to detect the two numbers and the operator, but I could not make a subtring for each number and the operator to be able to do the mathematical operation.

package analizadorlexicosintaxis01;

import java.lang.Math;

public class AnalizadorLexicoSintaxis01 {

public void Lexico(int i, int f, char[] lexema) {
    if (i <= f) {
        if (lexema[i] == '+' || lexema[i] == '-' || lexema[i] == '*' || lexema[i] == '/') {
            i++;
            //System.out.println("Operarodes reconocidos " + i);
            Lexico(i, f, lexema);
        } else if (lexema[i] == '0' || lexema[i] == '1' || lexema[i] == '2' || lexema[i] == '3') {
            i++;
            //System.out.println("[0, 3] Reconocidos " + i);
            Lexico(i, f, lexema);
        } else if (lexema[i] == '4' || lexema[i] == '5' || lexema[i] == '6' || lexema[i] == '7') {
            i++;
            //System.out.println("[4, 7] Reconocidos " + i);
            Lexico(i, f, lexema);
        } else if (lexema[i] == '8' || lexema[i] == '9') {
            i++;
            //System.out.println("[8, 9] Reconocidos " + i);
            Lexico(i, f, lexema);
        } else if (lexema[i] == '.') {
            i++;
            //System.out.println("punto Reconocido " + i);
            Lexico(i, f, lexema);
        } else {
            System.out.println("Error dentro del i < f");
        }
    } else if (f < 0) {
        System.out.println("Error Palabra vacia");
    } else {
        System.out.println("Lexico comprobado.");
        System.out.println("Iniciando revision de sintaxis (operadores y simbolo para decimal)");
        SintaxisA(0, f, lexema, 0, 0);
    }
   }

public void SintaxisA(int i, int f, char[] lexema, int opcont, int pcont) 
{
    if (opcont > 2) {
        System.out.println("Cadena invalida (operadores)");
    } else if (pcont > 1) {
        System.out.println("Cadena invalida (puntos)");

    } else if (i <= f) {
        //System.out.println(i);
        if (i == 0 && (lexema[i] == '.' || lexema[i] == '+' || lexema[i] == '*' || lexema[i] == '/')) {
            System.out.println("Cadena invalida (inicio no valido)");

        } else if (i == f && (lexema[i] == '.' || lexema[i] == '+' || lexema[i] == '-' || lexema[i] == '*' || lexema[i] == '/')) {
            System.out.println("Cadena invalida (final no valido)");

        } else if (lexema[i] == '+') {
            if (lexema[i + 1] == '+' || lexema[i + 1] == '*' || lexema[i + 1] == '/' || lexema[i + 1] == '.') {
                System.out.println("Cadena invalida ([+] segio por operador incompatible o punto)");
            } else {
                opcont++;
                pcont = 0;
                i++;
                //System.out.println("Conteo de opredor continuo:" + opcont);
                SintaxisA(i, f, lexema, opcont, pcont);
            }

        } else if (lexema[i] == '-') {
            if (lexema[i + 1] == '*' || lexema[i + 1] == '/' || lexema[i + 1] == '.') {
                System.out.println("Cadena invalida ([-] segio por operador incompatible o punto)");
            } else {
                opcont++;
                pcont = 0;
                i++;
                //System.out.println("Conteo de opredor continuo:" + opcont);
                SintaxisA(i, f, lexema, opcont, pcont);
            }

        } else if (lexema[i] == '*' || lexema[i] == '/') {
            if (lexema[i + 1] == '+' || lexema[i + 1] == '*' || lexema[i + 1] == '/' || lexema[i + 1] == '.') {
                System.out.println("Cadena invalida ([* o /] segio por operador incompatible o punto)");
            } else {
                opcont++;
                pcont = 0;
                i++;
                //System.out.println("Conteo de opredor continuo:" + opcont);
                SintaxisA(i, f, lexema, opcont, pcont);
            }
        } else if (lexema[i] == '.') {
            if (lexema[i + 1] == '+' || lexema[i + 1] == '-' || lexema[i + 1] == '*' || lexema[i + 1] == '/') {
                System.out.println("Cadena invalida (punto segido por operador)");
            } else {
                pcont++;
                i++;
                //System.out.println("Conteo de opredor continuo:" + opcont);
                SintaxisA(i, f, lexema, opcont, pcont);
            }
        } else {
            i++;
            opcont = 0;
            //System.out.println("procesando #" + i);
            SintaxisA(i, f, lexema, opcont, pcont);
        }
    } else {
        System.out.println("Sintaxis de operadores y simbolo decimal comprobado.");
        System.out.println("Iniciando comprobacion de Sintaxis para numeros.");
        SintaxisB(0, f, lexema, 0, 0, 0);
    }
}

public void SintaxisB(int i, int f, char[] lexema, int decimalescont, int contdp, int npalabra) {
    if (i <= f) {
        if (lexema[i] == '+' || lexema[i] == '-' || lexema[i] == '*' || lexema[i] == '/') {
            i++;
            decimalescont = 0;
            contdp = 0;
            //System.out.println("decimales: " + decimalescont + " if#1");
            SintaxisB(i, f, lexema, decimalescont, contdp, npalabra);
        } else if (lexema[i] == '.') {
            npalabra = Integer.toString(npalabra).length();
            if (npalabra != contdp) {
                System.out.println("error, cero innecesarios");
            } else {
                decimalescont++;
                i++;
                npalabra = 0;
                SintaxisB(i, f, lexema, decimalescont, contdp, npalabra);
            }

        } else if (decimalescont <= 0) {
            npalabra = npalabra * 10 + Integer.parseInt(String.valueOf(lexema[i]));
            contdp++;
            i++;
            //System.out.println(npalabra);
            SintaxisB(i, f, lexema, decimalescont, contdp, npalabra);
        } else {
            i++;
            SintaxisB(i, f, lexema, decimalescont, contdp, npalabra);
        }
    } else if (npalabra > 0 && i > f) {
        npalabra = Integer.toString(npalabra).length();
        if (npalabra != contdp) {
            System.out.println("error, ceros innecesarios");
        } else {
            System.out.println("Comprobacion de Sintaxis en numeros terminada");
            System.out.println("La cadena es aceptada");
        }
    } else {
        System.out.println("Comprobacion de Sintaxis en numeros terminada");
        System.out.println("La cadena es aceptada");
    }
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    AnalizadorLexicoSintaxis01 ab = new AnalizadorLexicoSintaxis01();
    String token = "-0.88/1";
    //System.out.println(token);
    char lex[] = token.toCharArray();
    System.out.println("Inicia ciclo. " + "long cadena: " + lex.length);
    ab.Lexico(0, lex.length - 1, lex);
}

}

The numbers are of variable length, I have not been able to obtain a subtring for each number and for the operator.

PrakashG
  • 1,642
  • 5
  • 20
  • 30
  • This will never work. It will never handle parentheses or operator precedence or unary operators correctly. Throw it all away and use a standard expression parser, or the scripting engine as suggested below. – user207421 Sep 02 '19 at 04:39
  • Is your task to create own parser (So things like regexes and javascript evaluations are out of scope)? – Piro Sep 02 '19 at 06:29
  • It is much easier if you convert it to integers first. – Pau Garcia Gozàlvez Apr 07 '20 at 11:18

2 Answers2

1

I don't know why you are trying to achieve this with lots of if-else statements. But with Java, there is built-in Javascript Engine to evaluate simple math expressions from String values. So if you only need to do a mathematical operation with a single string then I suggest the following,

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class Math {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine engine = scriptEngineManager.getEngineByName("JavaScript");
        String number = "-0.88/1";
        System.out.println(engine.eval(number));
     } 
}
Hasitha Jayawardana
  • 2,326
  • 4
  • 18
  • 36
-1

s.split("(?<=[-+*/])|(?=[-+*/]) - provide you array with 2 numbers and operator

Example:

enum Calculator {
    ADD('+', (x, y) -> x + y),
    SUBTRACT('-', (x, y) -> x - y),
    MULTIPLY('*', (x, y) -> x * y),
    DIVIDE('/', (x, y) -> x / y);

    char operation;
    BinaryOperator<Integer> operator;

    Calculator(char operation, BinaryOperator<Integer> operator) {
        this.operation = operation;
        this.operator = operator;
    }

    static int calculate(char c, int a, int b){
        return Stream
                .of(values())
                .filter(calculator -> calculator.operation == c)
                .findFirst().orElseThrow(RuntimeException::new)
                .operator
                .apply(a,b);
    }

    static int calculate(String s){
        String[] arr = s.split("(?<=[-+*/])|(?=[-+*/])");
        return calculate(arr[1].charAt(0), Integer.parseInt(arr[0]), Integer.parseInt(arr[2]));
    }
}

public static void main(String[] args) {
    String expression = "15+8881";
    System.out.println(Calculator.calculate(expression));
}
Eduard Dubilyer
  • 991
  • 2
  • 10
  • 21