Skip to content

Instantly share code, notes, and snippets.

@mohnoor94
Created December 30, 2017 17:36
Show Gist options
  • Select an option

  • Save mohnoor94/e8fc3348e9beafbb47001d00ac2d5f6f to your computer and use it in GitHub Desktop.

Select an option

Save mohnoor94/e8fc3348e9beafbb47001d00ac2d5f6f to your computer and use it in GitHub Desktop.
A simple Java calculator supports four operations (Summation, Subtraction, Multiplying, and Division) without using if or switch statements. (Using Reflection)
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Scanner scanner = new Scanner(System.in);
Class<?> operations = Class.forName("MainClass");
MainClass mainClass = new MainClass();
Method method = operations.getDeclaredMethod(scanner.next(), double.class, double.class);
System.out.println(method.invoke(mainClass, scanner.nextDouble(), scanner.nextDouble()));
}
double sum(double x, double y) {
return x + y;
}
double sub(double x, double y) {
return x - y;
}
double mul(double x, double y) {
return x * y;
}
double div(double x, double y) {
return x / y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment