Can I use a char in an arithmetic operation in Java?

Asked

Viewed 452 times

3

The following code doesn’t work, but I thought something along those lines:

char op = '*';
...
r = (y op x);

I want to change the characters of op to do different operations, it would be possible in some other way?

2 answers

5


In the language it does not. Only languages that allow the execution of arbitrary codes dynamically allow this, and in general in a different way.

Nor is there any reason to have this in a language. If you need something like this you should create a code that handles it and perform the operations you want. There are numerous ways to do this, but it is not what the question asks. What she does, there is no way.

In general you will have to create complex codes to do the job properly. None will facilitate coding work if this is the goal. And the code will certainly be less readable. It’s a bad idea to allow this directly.

  • Really, good explanation! The answer above I explain why I tried to do this, but your answer was helpful, helped me to understand better. Thank you very much!

1

The ideal in this case would be the use of a conditional case, ai yes you could use characters for your case follows the example:

    switch (op) {
      case '+': 
             r = primeiro + segundo;
             break;
      case '-': 
            r = primeiro - segundo;
            break;
      case '*': 
            r = primeiro * segundo;
            break;
     ....
    } 
  • Also remember to set the variables correctly, for example r as float to avoid splitting problems and treat problems with exceptions such as splitting by 0

Browser other questions tagged

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