I'm doing an exercise where I prompt the user to give me their operator of choice and two different numbers and then I output the result. I know I can easily do this exercise with a if else or a switch case however I'd really like to make it work this way. The problem is at my operator method, apparently in Java you can't pass in a parameter and use that parameter to call a method. Is there a way to make this work? If you were confused by the question I'd be glad to clarify.
import java.util.Scanner;
public class methods {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome, choose your operator, would you like to add, subtract, multiply, or divide?");
String typeofOperator = sc.nextLine();
System.out.print("Enter the first number: ");
int firstNumber = sc.nextInt();
System.out.print("Enter the second number: ");
int secondNumber = sc.nextInt();
operator(typeofOperator, firstNumber, secondNumber);
}
public static void operator(String typeofOperator, int firstNumber, int secondNumber) {
typeofOperator(firstNumber, secondNumber);
}
public static int add(int firstNumber, int secondNumber) {
int answer = firstNumber + secondNumber;
result(answer);
}
public static int subtract(int firstNumber, int secondNumber) {
int answer = firstNumber - secondNumber;
result(answer);
}
public static int multiply(int firstNumber, int secondNumber) {
int answer = firstNumber * secondNumber;
result(answer);
}
public static int divide(int firstNumber, int secondNumber) {
int answer = firstNumber / secondNumber;
result(answer);
}
public static void result(int result) {
System.out.println("This is the result: " + result);
}
}