Petersoj
Petersoj

Reputation: 51

Calculate and equation with a operator the user put in - Java

i am new to java and have been trying to learn it for a while now. This program that i am making is a basic calculator, but with the user inputting their choice of operation. I am having trouble finding out a way to put the 3 variables/operators together.

Here is what I've got.

package calulator;

import java.util.Scanner;


public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String first;
        String second;
        String operator;
        int numone;
        int numtwo;
        int answer;


        System.out.println("Enter first number.");
        first = scanner.nextLine();
        numone = Integer.parseInt(first);

        System.out.println("Enter operator.");
        operator = scanner.nextLine();
        //also don't know if i should convert this to a char or a string.

        System.out.println("Enter Second number.");
        second = scanner.nextLine();
        numtwo = Integer.parseInt(second);

        answer = numone + operator + numtwo;
        //I need a way so  ^^^^ that you can implement the operator.
        System.out.println(answer);
    }

}

Upvotes: 0

Views: 146

Answers (1)

switch(operator) {
case "+": answer = numone + numtwo; break;
case "-": answer = numone - numtwo; break;
case "*": answer = numone * numtwo; break;
case "/": answer = numone / numtwo; break;
// any other operators you want go here
default: throw new RuntimeException(operator+" isn't a valid operator!");
}

There is not a shorter way.

Upvotes: 2

Related Questions