Problem 1: Basic Calculator Given two integers, ’x’ and ’y’ and a character representing an arithmetic operator, ’op’. Return the result of ’x’ ’op’ ’y’ if possible, otherwise return -1. .java = BasicCalculator.java Examples (a) basicCalculator(2, 3, ’+’) returns 5 (b) basicCalculator(7, 3, ’%’) returns 1. (c) basicCalculator(5, 0, ’%’) prints an error message and returns -1 (5%0 is invalid).
public class BasicCalculator { public static int basicCalculator(int x, int y, char op) { if (op == '+') { return x + y; } else if (op == '-') { return x - y; } else if (op == '*') { return x * y; } else if (op == '/') { if (y == 0) { return -1; } return x / y; } else if (op == '%') { if (y == 0) { return -1; } return x % y; } return -1; } public static void main(String[] args) { System.out.println(basicCalculator(2, 3, '+')); System.out.println(basicCalculator(7, 3, '%')); System.out.println(basicCalculator(5, 0, '%')); } }
Get Answers For Free
Most questions answered within 1 hours.