You can read it in as a String
or char
and then use if statements to perform the operation, like so:
public static void main(String... args) {
String operator = args[0];
int num1 = 10;
int num2 = 20;
int result = 0;
if(operator.trim().equals("+")) {
result = num1 + num2;
} else if(operator.trim().equals("-")) {
result = num1 - num2;
} else if(operator.trim().equals("*")) {
result = num1 * num2;
} else if(operator.trim().equals("/")) {
result = num1 / num2;
}
// More operations here...
System.out.println(num1 + operator + num2 + "=" + result);
}
I would suggest, however, using the double
datatype over int
for precision's sake.