How to Pass Arithmetic Operators to a Method in Java

Is it possible to pass arithmetic operators to a method in java?

No, you can't do that in Java. The compiler needs to know what your operator is doing. What you could do instead is an enum:

public enum Operator
{
ADDITION("+") {
@Override public double apply(double x1, double x2) {
return x1 + x2;
}
},
SUBTRACTION("-") {
@Override public double apply(double x1, double x2) {
return x1 - x2;
}
};
// You'd include other operators too...

private final String text;

private Operator(String text) {
this.text = text;
}

// Yes, enums *can* have abstract methods. This code compiles...
public abstract double apply(double x1, double x2);

@Override public String toString() {
return text;
}
}

You can then write a method like this:

public String calculate(Operator op, double x1, double x2)
{
return String.valueOf(op.apply(x1, x2));
}

And call it like this:

String foo = calculate(Operator.ADDITION, 3.5, 2);
// Or just
String bar = String.valueOf(Operator.ADDITION.apply(3.5, 2));

Is there a way to pass arithmetic and logical operator as a method parameter in VBA?

An approach using classes:

Define a interface class

Op

Public Function eval(operand1, operand2)
End Function

For each desired operator, define a implementation. For example

OpMinus

Implements Op

Private Function Op_eval(operand1 As Variant, operand2 As Variant) As Variant
Op_eval = operand1 - operand2
End Function

OpPlus

Implements Op

Private Function Op_eval(operand1 As Variant, operand2 As Variant) As Variant
Op_eval = operand1 + operand2
End Function

Now some test routines in a module:

Sub test()
Dim Minus As New OpMinus
Dim Plus As New OpPlus
Dim o, v1, v2

For Each o In Array(Minus, Plus)
For Each v1 In Array(1, 2, 3)
For Each v2 In Array(1, 2, 3)
operate o, v1, v2
Next
Debug.Print ""
Next
Debug.Print ""
Next
End Sub

Sub operate(ByVal operator As Op, operand1, operand2)
Debug.Print operator.eval(operand1, operand2),
End Sub

Output:

 0            -1            -2            
1 0 -1
2 1 0

2 3 4
3 4 5
4 5 6

Note you may wish to use e.g. Double instead of Variant in the interface if you know on which type you'll be operating.

how to take Char/arithmetic operator as input from user without using Scanner

I'm not really sure why wouldn't you use Scanner in that situation... However, these are some other ways to read users input without using it:

  1. Use JOptionPane (read more about it here)

use:

 a = Integer.parseInt(JOptionPane.showInputDialog("Enter A :"))

instead of:

System.out.print("Enter A : "); 
a=s.nextInt();

use this for all you different inputs.


  1. Create a reader variable using System.in and define the variable a using a BufferedReader for obtaining the input:

    InputStreamReader isr = new InputStreamReader(System.in); 
    BufferedReader br = new BufferedReader (isr);
    try {
    a = Integer.parseInt(br.readLine());
    } catch (IOException e) {
    e.printStackTrace();
    }

As a side note, you have no need to perform all the operations before knowing which is the one the user wants. Change this:

double addition  = a+b;
double subtraction = a-b;
double multiplication = a*b;
double division = a/b;

switch(operator)
{
case '+' :
{
System.out.print("Total after Addition is : "+addition);
break;
}
case '-' :
{
System.out.print("Total after Subtraction is : " +subtraction);
break;
}
case '*' :
{
System.out.print("Total after Multiplication is : "+multiplication);
break;
}
case '/' :
{
System.out.print("Total after Division is : "+division);
break;
}
default :
{
System.out.print("Please select proper operator");
return;
}
}

for only this:

switch(operator)
{
case '+' :
{
double addition = a+b;
System.out.print("Total after Addition is : "+addition);
break;
}
case '-' :
{
double subtraction = a-b;
System.out.print("Total after Subtraction is : " +subtraction);
break;
}
case '*' :
{
double multiplication = a*b;
System.out.print("Total after Multiplication is : "+multiplication);
break;
}
case '/' :
{
double division = a/b;
System.out.print("Total after Division is : "+division);
break;
}
default :
{
System.out.print("Please select proper operator");
return;
}
}

Passing a math operator as a parameter

You can't pass an operator as a parameter, but you can pass a function:

function accumulate(list, accumulator){   // renamed parameter
var sum = 0;
for(var i = 0; i < list.length; i++){ // removed deprecated for…each loop
sum = accumulator(sum, list[i]);
}
print(sum);
}

accumulate(list, function(a, b) { return a + b; });

This is pretty close to what the Array.prototype.reduce function does, though not exactly. To mimic the behavior of reduce, you'd have to get the first element from list and use that as the seed for your accumulator, rather than always using 0:

function accumulate(list, accumulator, seed){
var i = 0, len = list.length;
var acc = arguments.length > 2 ? seed : list[i++];
for(; i < len; i++){
acc = accumulator(acc, list[i]);
}
print(acc);
}

This way, you could compute the product of list (your method would always return 0):

accumulate(list, function(a, b) { return a * b; });

Update: If you're developing for newer browsers that support ECMAScript 2015 / ES6 (or using a transpiler like Babel), you can also use 'arrow function' syntax to make your code a bit more compact:

accumulate(list, (a, b) => a * b);

Detecting type of operator stored as string in java

Another solution from J. Selva's response:

Improvements

  1. single class
  2. static block
  3. better abstraction

import java.util.HashMap;
import java.util.Map;

/**
* Created by SEA-HAWK on 23/8/15.
*/
public abstract class Expr {
public static Map<String,Object> op;
static{
op=new HashMap<>();
op.put("+", new Expr() {
@Override
public int evaluate(int a, int b) {
return a + b;
}
});
op.put("-", new Expr() {
@Override
public int evaluate(int a, int b) {
return a - b;
}
});
op.put("*", new Expr() {
@Override
public int evaluate(int a, int b) {
return a * b;
}
});

op.put("/", new Expr() {
@Override
public int evaluate(int a, int b) {
return a / b; // decimal point loss
}
});
}
abstract public int evaluate(int a, int b);
public static int exprEval(String expr){
String a[]=expr.split(",");
a[2]=a[2].replaceAll("\"","");
return ((Expr)op.get(a[2])).evaluate(Integer.parseInt(a[0]),Integer.parseInt(a[1]));
}
}

Main function:

public static void main(String[] args) {
String x="20,10,\"*\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"+\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"-\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"/\"";
System.out.println(x+"="+Expr.exprEval(x));
}

Output:

20,10,"*"=200
20,10,"+"=30
20,10,"-"=10
20,10,"/"=2

Note: change datatype for float/decimal value computation.

Java doing arithmetic using variable operators

something simple :

enum operation {
SUM,
SUB,
DIV,
MUL,
}

static String performOperation(operation op, String t1, String t2) {
// parse t1 & t2 into integers or whatever you use
switch(op) {
case SUM:
//do sum
break;
case SUB:
//do substraction
break;

// handle all of them....

}


Related Topics



Leave a reply



Submit