-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCalcDemo.java
More file actions
58 lines (50 loc) · 1.38 KB
/
Copy pathCalcDemo.java
File metadata and controls
58 lines (50 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.lang.reflect.Method;
import java.util.Scanner;
class Calculator{
public int add(int x, int y){
return x + y;
}
public int subtract(int x, int y){
return x - y;
}
public int multiply(int x, int y){
return x * y;
}
public int divide(int x, int y){
return x / y;
}
}
public class CalcDemo {
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the First No");
int firstNo = scanner.nextInt();
System.out.println("Enter the Second No");
int secondNo = scanner.nextInt();
System.out.println("Enter the Operation (add,subtract,multiply,divide) ");
String operation = scanner.next();
//Calculator calc = new Calculator();
int result = 0;
Object object = Class.forName("Calculator").newInstance();
Method method = object.getClass()
.getDeclaredMethod(operation, int.class,int.class);
// Downcasting + AutoBoxing
result = (Integer)method.invoke(object, firstNo,secondNo);
/*if(operation.equals("add")){
result = calc.add(firstNo, secondNo);
}
else
if(operation.equals("subtract")){
result = calc.subtract(firstNo, secondNo);
}
else
if(operation.equals("multiple")){
result = calc.multiply(firstNo, secondNo);
}
else
if(operation.equals("divide")){
result = calc.divide(firstNo, secondNo);
}*/
System.out.println("Result is "+result);
}
}