Java how to convert character into operator

Java how to convert character into operator

To convert a character into an operator in Java, you can use a switch statement or a series of if statements to compare the character to the desired operator characters and return the corresponding operator.

Here is an example of how you can use a switch statement to convert a character into an operator:

char c = '+';
Operator operator;

switch (c) {
  case '+':
    operator = Operator.ADDITION;
    break;
  case '-':
    operator = Operator.SUBTRACTION;
    break;
  case '*':
    operator = Operator.MULTIPLICATION;
    break;
  case '/':
    operator = Operator.DIVISION;
    break;
  default:
    operator = null;
    break;
}
S‮o‬urce:www.lautturi.com

This code defines a char variable c and an Operator variable operator. It then uses a switch statement to compare the value of c to various operator characters and assign the corresponding operator to the operator variable. If the character is not recognized as an operator, the operator variable is set to null.

You can also use a series of if statements to achieve the same result, like this:

char c = '+';
Operator operator;

if (c == '+') {
  operator = Operator.ADDITION;
} else if (c == '-') {
  operator = Operator.SUBTRACTION;
} else if (c == '*') {
  operator = Operator.MULTIPLICATION;
} else if (c == '/') {
  operator = Operator.DIVISION;
} else {
  operator = null;
}

This code uses a series of if statements to compare the value of c to various operator characters and assign the corresponding operator to the operator variable. If the character is not recognized as an operator, the operator variable is set to null.

You can define the Operator enum as follows:

public enum Operator {
  ADDITION,
  SUBTRACTION,
  MULTIPLICATION,
  DIVISION
}

This code defines an Operator enum with four values representing the four basic arithmetic operators.

Note that you may need to handle null values or other exceptions in your code if the character is not recognized as an operator. You can also add more operator characters and values to the switch statement.

Created Time:2017-11-03 22:21:04  Author:lautturi