Write a program to make a normal mathematics calculator.
For example:
Enter the numbers along with +, -, *, /, %, ^ symbols you want to be calculated:
1+2-3*4/5%6^7
Your calculation:
0.6
Remember to do using mathematics operator precedence(BODMAS) 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 line = in.nextLine();
int size = 0;
String[] equation = new String[line.length()];
for (int i = 0, j = 0; i < line.length(); i++) {
for (String operator : operators) {
if (line.charAt(i) == operator.charAt(0)) {
if (!operator.equals("-") || (i > 1 && line.charAt(i - 1) >= '0' && line.charAt(i - 1) <= '9')) {
equation[size++] = line.substring(j, i);
equation[size++] = line.substring(i, i + 1);
j = i + 1;
}
}
}
if (i == line.length() - 1) {
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
equation[size++] = line.substring(j, i + 1);
} else {
System.out.println("Wrong equation!");
System.exit(-1);
}
}
}
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