File size: 2,139 Bytes
765c82e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
Write the method

int calculate(int num1, int num2, String operator)

...which takes as parameters two integers and a string. 
The string has 4 possible values: "+", "-", "*" or "/"
The method calculates and returns the operator-defined arithmetic operation on the numbers.


Examples on method calls:
public static void main(String[] parameters){
    System.out.println(calculate(4, 5, "+"));
    System.out.println(calculate(8, 2, "-"));
    System.out.println(calculate(3, 4, "*"));
    System.out.println(calculate(10, 2, "/"));
}


Program outputs:
9
6
12
5







import java.util.Random;

public class Test{
    public static void main(String[] args){
        final Random r = new Random();
        
        
        Object[][] p = {{1,4,"+"}, {121,145,"-"}, {5,8,"*"}, {9,3,"/"}, {99,77,"-"}, 
            {2,4,"*"}, {20,5,"/"}, {1,2,"-"}, {9,3,"*"}};
        for (Object[] pa : p) {
            System.out.print("Testing with parameters ");
            System.out.println(pa[0] + ", " + pa[1] + ", " + pa[2]);
            int tulos = calculate((Integer) pa[0], (Integer) pa[1], (String) pa[2]);
            System.out.println("Result: " + tulos);
            System.out.println("");
        }
    }


    public static int calculate(int num1, int num2, String operator) {
        int result;
        if (operator.equals("+")) {
            result = num1 + num2;
        } 
        else if (operator.equals("-")) {
            result = num1 - num2;
        } 
        else if (operator.equals("*")) {
            result = num1 * num2;
        } 
        else if (operator.equals("/")) {
            result = num1 / num2;
        } 
        else {
            result = 0;
        }
        return result;
    }





    
}







Testing with parameters 1, 4, +
Result: 5

Testing with parameters 121, 145, -
Result: -24

Testing with parameters 5, 8, *
Result: 40

Testing with parameters 9, 3, /
Result: 3

Testing with parameters 99, 77, -
Result: 22

Testing with parameters 2, 4, *
Result: 8

Testing with parameters 20, 5, /
Result: 4

Testing with parameters 1, 2, -
Result: -1

Testing with parameters 9, 3, *
Result: 27