Search code examples
javaoperationmultiple-choice

Really confused on where to begin, multiple choice operations?


I have a prompt to "Write a program that performs the following operations: +, -, *, /, % (as defined by Java). Your program should first read the first number, then the operation, and then the second number. Both numbers are integers. If, for the operation, the user entered one of the symbols shown above, your program should perform the corresponding operation and compute the result. After that it should print the operation and the result. If the operation is not recognized, the program should display a message about it. You do not need to do any input validation for the integers."

An example output I'm given is:

Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10  =  16

How can I get started on this? I'm super confused and really new to java! Any help is greatly appreciated.


Solution

  • You generally first want to start reading input from STDIN:

    Scanner in = new Scanner(System.in);
    

    Then, I would read all parameters and afterwards perform the computation:

    System.out.print("Enter the first number: ");
    int left = Integer.parseInt(in.nextLine());
    
    System.out.print("Enter the operation: ");
    String operation = in.nextLine();
    
    System.out.print("Enter the second number: ");
    int right = Integer.parseInt(in.nextLine());
    

    Now that all input is collected, you can start acting.

    int result;
    switch(operation)
    {
        case "+": result = left + right; break;
        case "-": result = left - right; break;
        case "*": result = left * right; break;
        case "/": result = left / right; break;
        case "%": result = left % right; break;
        default: throw new IllegalArgumentException("unsupported operation " + operation);
    }
    System.out.println(left + " " + operation + " " + right + "  =  " + result);