How to make the program recognize 'x' as multiplication? [duplicate]

3

You can treat x like *, because the user will type x to multiply in a number, would you like the program to recognize x as a multiplication via code?

example double b = 5 x 5;

    
asked by anonymous 03.03.2015 / 13:20

2 answers

6

No. The multiplication operator in Java is * . However, you can do this for the end user.

For example, it can even type 5 x 5 as a multiplication, hence the program receives the string and replaces the x with * and mathematically evaluate the expression resulting from the substitution.

Why is it so?

Let's assume the following math instructions in a Java code:

int x = 10;
int a = 10 * x; //Compila corretamente, com a recebendo o valor 100;
int b = 10 x x; //Como deve ser entendido cada x? Um é multiplicação e outro é identificador?
                //Duas multiplicações? 
                //Dois identificadores?

The language should be uniform and precise. Otherwise, unpredictability occurs and no one knows why the hell the code does not do what it should be done.

How to solve this problem?

When you receive the user input, you can change it without the user's knowledge and display the correct result with a different expression than the one, as long as the expression used to compute is equivalent to the one you gave the program.

Example: Calculator with graphical interface

Let's assume a traditional calculator, with numbers from 0 to 9 and only the multiplication operator (for simplicity).

Each number places its value on the display and the multiplication button places the letter x . What should the = button do?

The algorithm would be:

  • Retrieve the string that the user created and assign to a variable;
  • Replace all x of variable with * . Easily done with replaceAll , and note that it is not necessary for this new String to be shown to the user;
  • Parsing the numbers that each * circles and multiplies;
  • Replace string with result;
  • String only has numbers? Show user;
  • Otherwise, go back to step 3.
  • 03.03.2015 / 13:27
    2

    By the question tag, I'm assuming you're deploying in Java.

    There are several ways to do this, which I will suggest is just one of them, not necessarily the best or simplest:

  • Parse the expression and convert the symbols that the user understands to the symbols that the language understands. Eg from "b = 5 x 5" to "b = 5 * 5".
  • Pass the processed string to a library that does this for you, such as BeanShell
  • A hypothetical example using BeanShell would be:

    Interpreter interp = new Interpreter();
    interp.eval("b = 5 * 5");
    System.out.println("resultado: b="+interpreter.get("b"));
    
        
    03.03.2015 / 13:30