Created
December 30, 2017 17:36
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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