Using a character operator to perform an operation Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using a character operator to perform an operation without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m having issues coming up with a solution for my calculator program that I’m working on. The issue I’m having is that I don’t know of a way to get the operation to work. I’ve tried concatenating it into a String, and then performing the operation that way, but you can’t do that. I’ve also tried having the operands and the operator (char b) in between the operands, but it wouldn’t perform the operation. The only solution that I have right now, is to do a series of checks that determine what the operator is, and then perform the equation using that operator, such as if (b == '-') { int answer = x-y;}. The only issue I have with doing it that way, is that it feels sloppy and like it could be done in a more efficient way.

/**
 * Makes sure that char b is a binary operator and returns the value made from x b y
 * 
 * @param  x   first operand of integer value
 * @param  b   the operation value
 * @param  y   second operand of integer value
 * @return     the operation of x b y where b is the binary operator, +,-,/,*,% 
 */
public int binaryOperation(int x, char b, int y)
{
    if (!(b == '+' || b == '-' || b == '/' || b == '*' || b == '%')) 
    {
        System.out.println("The character provided is not a valid binary operator. Please use one of the following characters:"
        + " '+', '-', '/', '*', or '%'.");
    }
    else 
    {
        int answer = 
        return answer;
    }
}

/**
 * Makes sure that b is an unary operator and returns the value made from x b y
 * 
 * @param  x   first operand of with an integer value
 * @param  b   the operation value
 * @param  y   second operand 
 * @return     the operation of x b y where b is the unary operator, + or -
 */
public int unaryOperation(int x, char b, int y)
{
    if (!(b == '+' || b == '-')) 
    {
        System.out.println("The character provided is not a valid unary operator. Please use one of the following characters:"
        + " '+' or '-'.");
    }
    else 
    {
        String function = System.out.println(x + b + y);
        int answer = (int) function;
        return answer;
    }
}

Answer

if (b == '+'){
   return x+y;
}
else if (b == '-') { 
   return x-y;
}

etc…

We are here to answer your question about Using a character operator to perform an operation - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji