Create basic java code for parsing and computing the 4 basic math operations from a…
- User
Create basic java code for parsing and computing the 4 basic math operations from a string in the format . Return the value as an appropriate number.
Assistant
Here's a basic Java implementation for parsing and computing the four basic math operations:
public class MathParser { public static Number parseAndCompute(String expression) { // Remove extra whitespace and split by spaces String[] parts = expression.trim().split("\\s+"); if (parts.length != 3) { throw new IllegalArgumentException("Invalid expression format. Expected: <operand> <operator> <operand>"); } double operand1 = parseNumber(parts[0]); String operator = parts[1]; double operand2 = parseNumber(parts[2]); double result = switch (operator) { case "+" -> operand1 + operand2; case "-" -> operand1 - operand2; case "*" -> operand1 * operand2; case "/" -> { if (operand2 == 0) { throw new ArithmeticException("Division by zero"); } yield operand1 / operand2; } default -> throw new IllegalArgumentException("Unsupported operator: " + operator); }; // Return as integer if result is a whole number, otherwise as double if (result == Math.floor(result) && !Double.isInfinite(result)) { return (int) result; } else { return result; } } private static double parseNumber(String str) { try { return Double.parseDouble(str); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid number: " + str); } } // Example usage public static void main(String[] args) { try { System.out.println(parseAndCompute("10 + 5")); // 15 System.out.println(parseAndCompute("20 - 8")); // 12 System.out.println(parseAndCompute("6 * 7")); // 42 System.out.println(parseAndCompute("15 / 3")); // 5 System.out.println(parseAndCompute("10 / 3")); // 3.3333333333333335 System.out.println(parseAndCompute("5.5 + 2.3")); // 7.8 } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } }This implementation:
- Splits the input string by whitespace to extract operands and operator
- Parses operands as doubles to handle both integers and decimals
- Uses a switch expression to perform the appropriate operation
- Handles division by zero with an exception
- Returns integers when the result is a whole number, otherwise returns a double
- Includes proper error handling for invalid formats and unsupported operators
The code supports expressions like "10 + 5", "3.14 * 2", "100 / 4", etc.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.