Spaces:
Running
Running
| 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 | |