Write a program to make a normal mathematics calculator.
For example:
Enter the numbers along with +, -, *, /, %, ^ symbols you want to be calculated:
5 + 4 - 7
Your calculation:
2
Remember to do using mathematics operator precedence not java operator precedence.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the numbers along with +, -, *, /, %, ^ symbols you want to be calculated:");
String[] operators = {"+", "-", "*", "/", "%", "^"};
String[] equation = in.nextLine().split(" ");
int size = equation.length;
while (size > 1) {
String operator = "";
int operatorIndex = -1;
for (int i = 0; i < size; i++) {
for (int j = 0; j < operators.length; j++) {
if (equation[i].equals(operators[j])) {
if (operator.length() == 0 || (operators[j].equals("^") && !operator.equals("^")) ||
((operators[j].equals("*") || operators[j].equals("/") || operators[j].equals("%"))
&& (operator.equals("+") || operator.equals("-")))) {
operator = equation[i];
operatorIndex = i;
}
break;
}
}
}
if (operatorIndex == -1) {
System.out.println("Wrong equation!");
System.exit(-1);
}
double result = 0;
switch (operator) {
case "+":
result = Double.parseDouble(equation[operatorIndex - 1]) + Double.parseDouble(equation[operatorIndex + 1]);
break;
case "-":
result = Double.parseDouble(equation[operatorIndex - 1]) - Double.parseDouble(equation[operatorIndex + 1]);
break;
case "*":
result = Double.parseDouble(equation[operatorIndex - 1]) * Double.parseDouble(equation[operatorIndex + 1]);
break;
case "/":
result = Double.parseDouble(equation[operatorIndex - 1]) / Double.parseDouble(equation[operatorIndex + 1]);
break;
case "%":
result = Double.parseDouble(equation[operatorIndex - 1]) % Double.parseDouble(equation[operatorIndex + 1]);
break;
case "^":
result = Math.pow(Double.parseDouble(equation[operatorIndex - 1]), Double.parseDouble(equation[operatorIndex + 1]));
break;
}
equation[operatorIndex - 1] = Double.toString(result);
for (int i = operatorIndex + 2; i < size; i++) {
equation[i - 2] = equation[i];
}
size -= 2;
}
System.out.println(equation[0]);
}
}
Comments
Leave a comment