Math wizardry in your pocket

Report a typo

Design a simple calculator program using functional decomposition. Create methods for addition, subtraction, multiplication, and division. The main method should take two numbers and an operator as input, then call the appropriate method based on the operator. Handle division by zero and invalid operators. Input format: 'number1 operator number2' (e.g., '5 + 3'). Output the result of the operation.

Sample Input 1:

5 + 3

Sample Output 1:

8.0

Sample Input 2:

10 / 2

Sample Output 2:

5.0
Write a program in Java 17
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] parts = input.split(" ");

double num1 = Double.parseDouble(parts[0]);
String operator = parts[1];
double num2 = Double.parseDouble(parts[2]);

double result = 0;

switch (operator) {
case "+":
result = add(num1, num2);
break;
case "-":
result = subtract(num1, num2);
break;
case "*":
result = multiply(num1, num2);
break;
case "/":
result = divide(num1, num2);
break;
default:
System.out.println("Invalid operator");
return;
}

System.out.println(result);
}

public static double add(double a, double b) {

Create a free account to access the full topic